今天看不进去论文,也学不进去新技术,于是先把题刷了,一会补别的。
-----------------------------------------------------我才不是分割线-------------------------------------------------
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
【题意】:就是给你两个链表,链表内的内容为一个多位数的逆序,比如342就表示为(2 -> 4 -> 3),现在让你算这两个多位数的和,
同时用相同的方法表示出来,也就是将和的逆序用链表表示出来。
【心路历程】看到题目一开始的想法就是考查模拟加法+链表操作的题,还算简单,链表操作就是一个尾部加链表的方法。
于是开始码代码,写完一交发现出现RE (TAT)。错误的样例为[0],[0]。想了半天不知道哪里错了。。。
后来发现我head指针没分配空间,额额额,改完一交,AC (^ ^)
------------------------------------------------------------------------------------------------------------------------
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode * res = (struct ListNode *)malloc(sizeof(struct ListNode));
struct ListNode * ans = NULL;
int judge = ;
int save = ;
int add1,add2,sum;
if(l1 == NULL && l2 == NULL) return NULL;
while(l1 != NULL || l2 != NULL) {
if(l1 == NULL) {
add1 = ;
add2 = l2->val;
l2 = l2->next;
}else if(l2 == NULL){
add1 = l1 ->val;
add2 = ;
l1 = l1->next;
}else {
add1 = l1->val;
add2 = l2->val;
l1 = l1->next;
l2 = l2->next;
}
sum = add1 + add2 + save;
save = sum / ;
struct ListNode * temp = (struct ListNode *)malloc(sizeof(struct ListNode));
temp->val = sum % ;
temp->next = NULL;
res->next = temp;
if(judge == ) {
ans = temp;
judge = ;
}
res = res->next;
}
if(save){
struct ListNode * temp = (struct ListNode *)malloc(sizeof(struct ListNode));
temp->val = save;
temp->next = NULL;
res->next = temp;
}
return ans;
}