Add Two Numbers II

来源:互联网 发布:打谱软件手机版 编辑:程序博客网 时间:2024/05/16 09:05

You are given two linked lists representing two non-negative numbers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)Output: 7 -> 8 -> 0 -> 7
算法:先算哪个长,然后指针移动到相等的地方,然后先把list加起来,然后reverse过来,进行进位运算,然后再reverse回来就结果。题目只是要求不reverse input list,但是并没有限制reverse计算出来的list。所以原来的list还是保持没变;操作的只是生成的结果list。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {        if(l1 == null && l2 == null) return null;        if(l1 == null && l2 != null) return l2;        if(l1 != null && l2 == null) return l1;        int m = getLength(l1);        int n = getLength(l2);        if(m > n){            return addTwoList(l1, m, l2, n);        } else {            return addTwoList(l2, n, l1, m);        }    }        public int getLength(ListNode l1){        int count = 0;        while(l1!=null){            l1 = l1.next;            count++;        }        return count;    }        public ListNode reverse(ListNode head){        if(head == null || head.next == null) return head;        ListNode dump = new ListNode(0);        dump.next = head;        ListNode pre = head;        while(pre.next!=null){            ListNode cur = pre.next;            pre.next = cur.next;            cur.next = dump.next;            dump.next = cur;        }        return dump.next;    }        public ListNode addTwoList(ListNode l1, int m,  ListNode l2, int n) {        // make assumption, m > n;        ListNode dump = new ListNode(0);        ListNode cur = dump;        int step = m-n;        while(step >0){            cur.next = l1;            cur = cur.next;            l1 = l1.next;            step--;        }        while(l1!=null && l2!=null){            int sum = l1.val + l2.val;            l1 = l1.next;            l2 = l2.next;            cur.next = new ListNode(sum);            cur = cur.next;        }        ListNode newhead = reverse(dump.next);        int carry = 0;        cur = newhead;        while(cur!=null){            int sum = (cur.val + carry);            cur.val = sum % 10;            carry = sum / 10;            if(cur.next == null){                if(carry != 0){                    cur.next = new ListNode(1);                    break;                }            }            cur = cur.next;        }        return reverse(newhead);    }}


0 0