首页 > 其他 > 详细

Leetcode(2) – Add Two Numbers

时间:2016-02-03 06:38:34      阅读:208      评论:0      收藏:0      [点我收藏+]

https://leetcode.com/problems/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

 

这道题思路比较简单,两个链表从头到尾相加即可。容易出错的地方是最后两个链表走完要记得check offset是否为0. 不为0还要加上一个node. 此外这种从头构造链表的题目,技巧是加一个dummy node。代码如下,时间复杂度O(n), 空间复杂度O(1)

 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 dummy = new ListNode(0);
12         ListNode tail = dummy;
13         int offset = 0;
14         while(l1 != null || l2 != null){
15             int total = 0;
16             if(l1 != null){
17                 total += l1.val;
18                 l1 = l1.next;
19             }
20             if(l2 != null){
21                 total += l2.val;
22                 l2 = l2.next;
23             }
24             total += offset;
25             ListNode node = new ListNode(total%10);
26             offset = total / 10;
27             tail.next = node;
28             tail = node;
29         }
30         if(offset != 0){
31             ListNode node = new ListNode(offset);
32             tail.next = node;
33         }
34         return dummy.next;
35     }
36 }

 

Leetcode(2) – Add Two Numbers

原文:http://www.cnblogs.com/xinhuan23/p/5178876.html

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