今天看不进去论文,也学不进去新技术,于是先把题刷了,一会补别的。
-----------------------------------------------------我才不是分割线-------------------------------------------------
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 (^ ^)
------------------------------------------------------------------------------------------------------------------------
代码如下:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * struct ListNode *next; 6 * }; 7 */ 8 struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { 9 struct ListNode * res = (struct ListNode *)malloc(sizeof(struct ListNode)); 10 struct ListNode * ans = NULL; 11 int judge = 0; 12 int save = 0; 13 int add1,add2,sum; 14 if(l1 == NULL && l2 == NULL) return NULL; 15 while(l1 != NULL || l2 != NULL) { 16 if(l1 == NULL) { 17 add1 = 0; 18 add2 = l2->val; 19 l2 = l2->next; 20 }else if(l2 == NULL){ 21 add1 = l1 ->val; 22 add2 = 0; 23 l1 = l1->next; 24 }else { 25 add1 = l1->val; 26 add2 = l2->val; 27 l1 = l1->next; 28 l2 = l2->next; 29 } 30 sum = add1 + add2 + save; 31 save = sum / 10; 32 struct ListNode * temp = (struct ListNode *)malloc(sizeof(struct ListNode)); 33 temp->val = sum % 10; 34 temp->next = NULL; 35 res->next = temp; 36 if(judge == 0) { 37 ans = temp; 38 judge = 1; 39 } 40 res = res->next; 41 } 42 if(save){ 43 struct ListNode * temp = (struct ListNode *)malloc(sizeof(struct ListNode)); 44 temp->val = save; 45 temp->next = NULL; 46 res->next = temp; 47 } 48 return ans; 49 }