标签:头结点 == two sum style init sizeof 返回结果 turn leetcode
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 }
标签:头结点 == two sum style init sizeof 返回结果 turn leetcode
原文地址:http://www.cnblogs.com/tuhooo/p/7123921.html