题目
You are given two non-empty linked lists representing two non-negative integers. 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.
你有两个非空链表,表示两个非负整数,数字以相反的顺序存储,每个节点中包含一个单独的数字。两个数字相加,并且返回结果一个链表。
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
你可以假设两个数字的最开始不包括0,除了0自己。
Example
例子
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
代码
正常思想一个节点一个节点走,注意需要设置一个进位项。
/**
* 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 n = new ListNode(0);
ListNode p = l1,q=l2,c=n;
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;
c.next = new ListNode(sum%10);
c = c.next;
if(q!=null) q=q.next;
if(p!=null) p=p.next;
}
if(carry>0)
{
c.next = new ListNode(carry);
}
return n.next;
}
}