You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain 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
给定两组链表,分别代表两组非负数。数字以反序存储,并且每一个点只包含一个数字。将这两组数相加,以链表的形式返回。
答案
/**
* 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) {
ListNode p = l1;
ListNode q = l2;
ListNode resultNode = new ListNode(0);//创建链表相加后第一个链表
ListNode cur = resultNode;//此时cur也指向第一个链表
int carry = 0;
while(p!=null || q!=null) {
int x = (p != null)? p.val:0;
int y = (q != null)? q.val:0;
int sum = x + y +carry;
carry = sum / 10;
cur.next = new ListNode(sum % 10);
cur = cur.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
if (carry > 0) cur.next = new ListNode(carry);//如果最后一位大于10,新增加一个链表
return resultNode.next;//此时cur已经指向了整个结果链表的最后一位,因此返回应该返回还指向整个结果链表首位的resultNode.next
//如果是return resultNode,则最后结果的首位多一个0,变成了四位
}
}