Reverse my linked lists. O(n) Java Solution, O(1) space complexity except for output


  • 0
    A

    My algorithm is pretty straight forward. I reverse l1 and l2, add them together and reverse them in the end.

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            l1 = reverse(l1);
            l2 = reverse(l2);
            ListNode head = null;
            ListNode runner1 = l1;
            ListNode runner2 = l2;
            int carry = 0;
            while (runner1 != null || runner2 != null) {
                int number1 = runner1 != null ? runner1.val : 0;
                int number2 = runner2 != null ? runner2.val : 0;
                int sum = number1 + number2 + carry;
                if (head == null) {
                    head = new ListNode(sum % 10);
                } else {
                    ListNode node = new ListNode(sum % 10);
                    node.next = head;
                    head = node;
                }
                
                carry = sum / 10;
                runner1 = runner1 != null ? runner1.next : null;
                runner2 = runner2 != null ? runner2.next : null;
            }
            if (carry == 1) {
                ListNode node = new ListNode(1);
                node.next = head;
                head = node;
            }
            
            l1 = reverse(l1);
            l2 = reverse(l2);
            return head;
        }
        
        public ListNode reverse(ListNode head) {
            ListNode pre = null;
            ListNode current = head;
            ListNode next = null;
            while (current != null) {
                next = current.next;
                current.next = pre;
                pre = current;
                current = next;
            }
            return pre;
        }
    

Log in to reply
 

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