题目链接: https://oj.leetcode.com/problems/add-two-numbers/
问题:
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contains a single digit. Add the two numbers and return it as a linked list.
Input: (2->4->3) + (5->6->4) Output: 7->0->8
解题思路:
1)用变量carry记录是否进位
2)从链表头开始计算两链表相应位置上的数字之和
注意
1)输入两链表长度不相等
2)两链表相加之后的结果链表长度可能大于两链表(例如:(9->9) + (1) = (0->0->1)
1 public ListNode addTwoNumbers(ListNode l1, ListNode l2){ 2 ListNode dummyHead = new ListNode(0); 3 ListNode p = l1; 4 ListNode q = l2; 5 ListNode curr = dummyHead; 6 int carry = 0; 7 while(p != null || q != null){ 8 int x = (p != null) ? p.val : 0; 9 int y = (q != null) ? q.val : 0; 10 int digit = carry + x + y; 11 curr.next = new ListNode(digit % 10); 12 curr = curr.next; 13 carry = digit / 10; 14 if(p != null){ 15 p = p.next; 16 } 17 if(q != null){ 18 q = q.next; 19 } 20 } 21 if(carry > 0){ 22 curr.next = new ListNode(carry); 23 } 24 return dummyHead.next; 25 }