Java reverse list solution


  • 0
    D
    public class Solution {
        public String addStrings(String num1, String num2) {
            if (num1 == null && num1.length() == 0) {
                return num2;
            }
            if (num2 == null && num2.length() == 0) {
                return num1;
            }
            ListNode list1 = getRevList(num1);
            ListNode list2 = getRevList(num2);
            ListNode list3 = addRevLists(list1, list2);
            return getNumberFromRevList(list3);
        }
    
        private ListNode getRevList(String str) {
            ListNode dummy = new ListNode(0);
            ListNode prev = dummy;
            for (int i = 0; i < str.length(); i++) {
                ListNode node = new ListNode((int)(str.charAt(i) - '0'));
                prev.next = node;
                prev = node;
            }
            return reverseList(dummy.next);
        }
    
        private ListNode addRevLists(ListNode list1, ListNode list2) {
            ListNode dummy = new ListNode(0);
            _addRevLists(dummy, list1, list2, 0);
            return dummy.next;
        }
    
        private void _addRevLists(ListNode prev, ListNode list1, ListNode list2, int carry) {
            if (list1 == null && list2 == null && carry == 0) {
                return;
            }
            ListNode node = new ListNode((list1 == null ? 0 : list1.val) + (list2 == null ? 0 : list2.val) + carry);
            if (node.val >= 10) {
                node.val -= 10;
                carry = 1;
            } else {
                carry = 0;
            }
            prev.next = node;
            prev = node;
            _addRevLists(prev, list1 == null ? null : list1.next, list2 == null ? null : list2.next, carry);
        }
    
        private String getNumberFromRevList(ListNode node) {
            ListNode list = reverseList(node);
            StringBuffer sb = new StringBuffer();
            while (list != null) {
                sb.append(Integer.toString(list.val));
                list = list.next;
            }
            return sb.toString();
        }
    
        private ListNode reverseList(ListNode node) {
            if (node == null || node.next == null) {
                return node;
            }
            ListNode p1 = null;
            ListNode p2 = node;
            ListNode p3 = node.next;
            while (p2 != null) {
                p2.next = p1;
                p1 = p2;
                p2 = p3;
                p3 = p3 == null ? null : p3.next;
            }
            return p1;
        }
    
        class ListNode {
            int val;
            ListNode next;
            public ListNode(int val) {
                this.val = val;
            }
        }
    }
    

Log in to reply
 

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