leetcode - 面试题 02.05. 链表求和
题目
代码
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69#include <iostream> #include <vector> using namespace std; typedef struct ListNode { int val; struct ListNode *next; }ListNode, *LinkList; void create(LinkList &head){ int n; cin>>n; head = new ListNode; head->next = NULL; ListNode *tail = head; for(int i = 0; i < n; i++){ ListNode *p = new ListNode; cin>>p->val; p->next = NULL; tail->next = p; tail = p; } } ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { int sum = 0, flag = 0, num = 0; int x, y; ListNode *head = new ListNode; head->next = NULL; ListNode *tail = head; while(l1 || l2 || flag){ if(l1){ x = l1->val; l1 = l1->next; }else{ x = 0; } if(l2){ y = l2->val; l2 = l2->next; }else{ y = 0; } sum = x + y + flag; flag = sum / 10; num = sum % 10; ListNode *p = new ListNode; p->val = num; p->next = NULL; tail->next = p; tail = p; } return head->next; } int main(){ ListNode *l1, *l2, *res; create(l1); create(l2); l1 = l1->next; l2 = l2->next; res = addTwoNumbers(l1, l2); while(res){ cout<<res->val<<" "; res = res->next; } return 0; }
最后
以上就是聪明金针菇最近收集整理的关于leetcode - 面试题 02.05. 链表求和leetcode - 面试题 02.05. 链表求和的全部内容,更多相关leetcode内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复