1
2
3
4
5
|
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
Subscribe to see which companies asked this question
|
题意:实际上就是342+465=807然后倒序输出。【一开始也没有看明白。】
参考别人的。一开始题意都没看明白。。。。。。
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
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct
ListNode* addTwoNumbers(
struct
ListNode* l1,
struct
ListNode* l2) {
struct
ListNode *l3 = (
struct
ListNode *)
malloc
(
sizeof
(
struct
ListNode));
l3->val=0;
l3->next=NULL;
//这边因为l3是一直往后遍历的,所以返回头的话要加个head指示一下。
struct
ListNode* head = l3;
l3->val=l1->val+l2->val;
//while循环判断是否申请新的节点
l1=l1->next;
l2=l2->next;
while
(l1||l2||l3->val>9){
l3->next=(
struct
ListNode *)
malloc
(
sizeof
(
struct
ListNode));
l3->next->val=0;
l3->next->next=NULL;
if
(l1){
l3->next->val+=l1->val;
l1=l1->next;
}
if
(l2){
l3->next->val+=l2->val;
l2=l2->next;
}
if
(l3->val>9){
l3->next->val+=l3->val/10;
l3->val=l3->val%10;
}
l3=l3->next;
}
return
head;
}
|
PS:主要是搞清楚有几种情况。9+8这种需要申请节点;12+9这种不等长的;
注意C语言链表的使用。。。
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
|
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public
class
Solution {
public
ListNode addTwoNumbers(ListNode l1, ListNode l2) {
直接模拟加法就行。先申请一个head
ListNode head=
new
ListNode(
0
);
int
carry=
0
;
ListNode p1=l1,p2=l2,p3=head;
while
(l1!=
null
|| l2!=
null
){
if
(l1!=
null
){
carry+=l1.val;
l1=l1.next;
}
if
(l2!=
null
){
carry+=l2.val;
l2=l2.next;
}
p3.next=
new
ListNode(carry%
10
);
p3=p3.next;
carry=carry/
10
;
}
if
(carry==
1
){
p3.next=
new
ListNode(
1
);
}
return
head.next;
}
}
|
JAVA版本的。
本文转自 努力的C 51CTO博客,原文链接:http://blog.51cto.com/fulin0532/1864621