Leetcode(2) – Add Two Numbers

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 }

 

posted @ 2016-02-03 02:45  破釜沉舟——不忘初心  阅读(127)  评论(0)    收藏  举报