LeetCode two sum
阿新 • • 發佈:2017-07-06
all 位標誌 找到 指針 return cnblogs 存儲 ini !=
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 r = {0, NULL}; // 作為返回結果的頭結點 10 struct ListNode *p = &r; //指針運算的p 11 12 int flag = 0; // 進位標誌 13 14 while (l1 != NULL && l2 != NULL) { 15 16 int tmp = l1->val + l2->val + flag; // 如果都不為空則進行求和運算 17 18 // 判斷是否有進位 19 if(tmp >= 10) { 20 flag = 1; 21 tmp = tmp % 10; 22 } else{ 23 flag = 0; 24 } 25 26 // 新增一個結點來r存儲值 27 struct ListNode * node = (struct ListNode *) malloc(sizeof(struct ListNode)); 28 node->next = NULL; 29 node->val = tmp; 30 p->next = node; 31 p = p->next; 32 33 l1 = l1->next;34 l2 = l2->next; 35 } 36 37 // 找到仍有結點的鏈表 38 struct ListNode *q; 39 if(l1 != NULL) 40 q = l1; 41 else 42 q = l2; 43 44 while (q != NULL) { 45 int tmp = q->val + flag; 46 47 if(tmp >= 10) { 48 flag = 1; 49 tmp = tmp % 10; 50 } else { 51 flag = 0; 52 } 53 struct ListNode * node = (struct ListNode *) malloc(sizeof(struct ListNode)); 54 node->next = NULL; 55 node->val = tmp; 56 p->next = node; 57 p = p->next; 58 59 q = q->next; 60 } 61 62 if(flag == 1) { 63 struct ListNode * node = (struct ListNode *) malloc(sizeof(struct ListNode)); 64 node->next = NULL; 65 node->val = flag; 66 p->next = node; 67 p=p->next; 68 } 69 70 return r.next; 71 }
LeetCode two sum