Title:
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8
该题目是给定两个非零链表,每个链表的节点组合是一个数字,要求得到两个链表相加的结果,比如,2->4->3 表示 342,5->6->4表示465,相加为807,转换成链表也就是7->0->8。
该题比较复杂,属于medium程度,要考虑到进位,链表长度不同等问题,涉及到链表这种数据结构,其实用python或c++会比较容易实现,比如分配空间,c++的new就比c的malloc方便很多,不用考虑数据类型和数据大小,而malloc返回的是无类型的void*,同时要指定大小。牵扯到复杂的数据结构,高级语言的优势就体现出来了。
贴出本人的solutions:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* p1;
struct ListNode* p2;
struct ListNode* p3;
struct ListNode* p4;
struct ListNode* res = (struct ListNode*)malloc(sizeof(struct ListNode));
res->val =0;
res->next=NULL;
struct ListNode* head = res;
int len1 = 0;
int len2 = 0;
int count_jin = 0;
int judge = 0;
p3 = l1;
p4 = l2;
while (l1->next) {
len1++;
l1 = l1->next;
}
while (l2->next) {
len2++;
l2 = l2->next;
}
if (len1 < len2) {
p1 = p4;
p2 = p3;
}
else {
p1 = p3;
p2 = p4;
}
while (p1) {
if (p2) {
res->val = p1->val + p2->val + count_jin;
}
else {
res->val = p1->val + count_jin;
}
if (res->val >= 10) {
res->val = res->val - 10;
count_jin = 1;
}
else
count_jin = 0;
p1 = p1->next;
if(p1) {
res->next = (struct ListNode*)malloc(sizeof(struct ListNode));
res->next->next = NULL;
res=res->next;
}
if (p2)
p2 = p2->next;
}
if (count_jin ==1) {
res->next = (struct ListNode*)malloc(sizeof(struct ListNode));
res->next->val = count_jin;
res->next->next = NULL;
res=res->next;
}
return head;
}
分析几个要注意的点:
首先是两个链表的长度问题。链表相加,很明显是链表里的数据val相加,那么就是个嵌套循环,对于长度不同的链表,长的要放在第一层循环,这样能够保证全部数据能够遍历到。因此要加上个判断,长的链表作为第一层循环。
while (l1->next) {
len1++;
l1 = l1->next;
}
while (l2->next) {
len2++;
l2 = l2->next;
}
if (len1 < len2) {
p1 = p4;
p2 = p3;
}
else {
p1 = p3;
p2 = p4;
}
其次是进位问题,也就是如果相加的结果大于等于10的话,就要进位,count_jin=1,那么下一位在相加时就要加上这个进位。如果没有下一位,比如9+1, 这个时候,就要创建为链表创建一个新的节点,用来存放新的进位1,不然9+1 得到的结果是0,进位没有得到保存。
if (count_jin ==1) {
res->next = (struct ListNode*)malloc(sizeof(struct ListNode));
res->next->val = count_jin; res->next->next = NULL; res=res->next; }
最后也是最重要的一点,就是新节点的创建。
要用malloc分配空间,代码为:
res->next = (struct ListNode*)malloc(sizeof(struct ListNode));
进行强制类型转换成struct ListNode*,同时要指定分配空间的大小,sizeof(struct ListNode)。
然后要将next的next设置为NULL,不然会报错:
因此将分配的结构体中的next指针指向NULL
res->next->next = NULL;
这样就完成了一个新的节点的创建。