码迷,mamicode.com
首页 > 其他好文 > 详细

Add Two Numbers(Linked List)

时间:2017-02-18 22:54:29      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:code   技术   ber   image   next   pre   head   res   eve   

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)

标签:code   技术   ber   image   next   pre   head   res   eve   

原文地址:http://www.cnblogs.com/guoluo20170216/p/6414150.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!