Leetcode 2. 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
分析:两个链表中包含的数不一定一样多!!
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 12 int flag = 0, add; 13 //创建一个节点要开辟空间,不能只定义一个指针,否则没有指向 14 ListNode* head = new ListNode(0), *p, *q, *l3; 15 p = l1; 16 q = l2; 17 l3 = head; 18 while(p != NULL && q != NULL){ 19 l3->next = new ListNode((p->val + q->val + flag) % 10); 20 flag = (p->val + q->val + flag) / 10; 21 l3 = l3->next; 22 p = p->next; 23 q = q->next; 24 } 25 while(p != NULL){ 26 l3->next = new ListNode((p->val + flag) % 10); 27 flag = (p->val + flag) / 10; 28 l3 = l3->next; 29 p = p->next; 30 } 31 while(q != NULL){ 32 l3->next = new ListNode((q->val + flag) % 10); 33 flag = (q->val + flag) / 10; 34 l3 = l3->next; 35 q = q->next; 36 } 37 if(flag == 1){//加入两个链表【9,9】,【8,9】,可知最后两个数加起来为19,需要在再创建一个节点最后放置1 38 l3->next = new ListNode(flag); 39 l3 = l3->next; 40 } 41 return head->next; 42 43 } 44 };
越努力,越幸运