首页 > 其他 > 详细

2.Add Two Numbers-两个单链表相加

时间:2015-11-10 12:05:25      阅读:268      评论:0      收藏:0      [点我收藏+]

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

 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         ListNode c1 = l1;//定义两个指针变量 c1 c2
12         ListNode c2 = l2;
13         ListNode head = new ListNode(0);//定义一个新链表的头结点
14         ListNode d = head;//新链表的指针变量
15         int sum = 0;
16         while(c1 != null || c2 != null) {
17             if(c1 != null) {
18                 sum = sum + c1.val;
19                 c1 = c1.next;
20             }
21             if(c2 != null) {
22                 sum = sum + c2.val;
23                 c2 = c2.next;
24             }
25             d.next = new ListNode(sum%10);
26             d = d.next;
27             sum = sum /10;
28         }
29         if(sum == 1) {
30             d.next = new ListNode(1);
31         }
32         return head.next;
33         
34         
35     }
36 }

 

2.Add Two Numbers-两个单链表相加

原文:http://www.cnblogs.com/leehfly/p/4952113.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!