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

题目意思很简单,有点类似两个链表归并

 

个人思路:

1,同时从头结点开始遍历两个链表,将对应的两个结点以及进位相加,和记为temp,进位记为flag,temp % 10是结果链表对应结点的值,temp / 10是进位flag

2,不断循环,直到某个链表遍历完,然后将未遍历完链表的剩余部分与进位相加,处理方式同1,直到该链表也遍历完

3,注意一下最后的进位flag是否为1,为1则表示最后结点的和是有进位的,需要再向高位进1

代码:

 1 #include <stddef.h>
 2 
 3 struct ListNode
 4 {
 5     int val;
 6     ListNode *next;
 7     ListNode(int x) : val(x), next(NULL) {}
 8 };
 9 
10 class Solution {
11 public:
12     ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
13         if (!l1)
14         {
15             return l2;
16         }
17 
18         if (!l2)
19         {
20             return l1;
21         }
22 
23         ListNode *l1Current = l1;
24         ListNode *l2Current = l2;
25         ListNode *result = NULL;
26         ListNode *head = NULL;
27         int flag = 0; //进位
28         int temp = 0;
29 
30         while (l1Current && l2Current)
31         {
32             temp = l1Current->val + l2Current->val + flag;
33             if (result)
34             {
35                 result->next = new ListNode(temp % 10);
36                 result = result->next;
37                 flag = temp / 10;
38             }
39             else
40             {
41                 result = new ListNode(temp % 10);
42                 head = result;
43                 flag = temp / 10;
44             }
45             l1Current = l1Current->next;
46             l2Current = l2Current->next;
47         }
48 
49         while (l1Current)
50         {
51             temp = l1Current->val + flag;
52             result->next = new ListNode(temp % 10);
53             result = result->next;
54             flag = temp / 10;
55             l1Current = l1Current->next;
56         }
57 
58         while (l2Current)
59         {
60             temp = l2Current->val + flag;
61             result->next = new ListNode(temp % 10);
62             result = result->next;
63             flag = temp / 10;
64             l2Current = l2Current->next;
65         }
66 
67         if (flag) //最后的结点和有进位
68         {
69             result->next = new ListNode(1);
70         }
71 
72         return head;
73     }
74 };
View Code

 

网上基本是这个思路

posted on 2014-09-05 10:24  laihaiteng  阅读(122)  评论(0编辑  收藏  举报

导航