首页 > 代码库 > Add Two Numbers(Linked List)

Add Two Numbers(Linked List)

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 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

即实现342+465=807

首先第一种方法 两个单个节点还有进位相加实现如下:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
11         if(l1==null&&l2==null){
12             return null;
13         }
14         if(l1==null){
15             return l2;
16         }
17         if(l2==null){
18             return l1;
19         }
20         ListNode n1=l1;
21         ListNode n2=l2;
22         ListNode head=new ListNode(0);
23         ListNode result=head;
24         int carry=0;
25         while(carry!=0||n1!=null||n2!=null){
26             int v1=0;
27             if(n1!=null){
28                 v1=n1.val;
29                 n1=n1.next;
30             }
31             int v2=0;
32             if(n2!=null){
33                 v2=n2.val;
34                 n2=n2.next;
35             }
36             int temp=(v1+v2+carry);
37             carry=temp/10;//此处注意定义temp实现避免重发利用carry时carry值更新
38             head.next=new ListNode(temp%10);  
39             head=head.next;//此处必须先调用构造方法后移动节点 构造方法实现类的初始化 
40         }
41         return result.next;
42     }
43 }
运行结果:
Your input
[2,4,3]
[5,6,4]
Your answer
[7,0,8]


错误实例:
  head=head.next;
head.next=new ListNode(temp%10);
结果为【】。
技术分享

 

 

Add Two Numbers(Linked List)