面试题 02.05. 链表求和
思路很简单,首先输出res.next可以避免链表头结点是0的问题。
然后不能在第一个while循环结束后直接把剩下的链表接上来,因为可能存在进位,仍然需要一步一步递加。
最后一位也有可能产生进位,如果有进位直接new ListNode(1)即可。
面试题 02.05. 链表求和
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode tmp = new ListNode(0); ListNode res = tmp; int carry = 0, num = 0; while(l1 != null && l2 != null){ num = l1.val + l2.val + carry; carry = num / 10; ListNode node = new ListNode(num % 10); tmp.next = node; l1 = l1.next; l2 = l2.next; tmp = tmp.next; } while(l1 != null){ num = carry + l1.val; carry = num / 10; ListNode node = new ListNode(num % 10); tmp.next = node; l1 = l1.next; tmp = tmp.next; } while(l2 != null){ num = carry + l2.val; carry = num / 10; ListNode node = new ListNode(num % 10); tmp.next = node; l2 = l2.next; tmp = tmp.next; } if(carry != 0) tmp.next = new ListNode(1); return res.next; } }