C# - stack (not nearly as good as the 2 pointer solution)


  • 0
    public ListNode PlusOne(ListNode head) {
        Stack<ListNode> stack = new Stack<ListNode>();
        ListNode curr = head;
        while (curr != null)
        {
            stack.Push(curr);
            curr = curr.next;
        }
        
        int carry = 1;
        while (stack.Count() > 0 && carry > 0)
        {
            ListNode node = stack.Pop();
            int x = (node.val + carry) % 10;
            carry = (node.val + carry) / 10;
            node.val = x;
        }
        
        if (carry > 0)
        {
            ListNode node = new ListNode(carry);
            node.next = head;
            return node;
        }
        else
        {
            return head;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.