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
考查的是連結串列的合併,類似多項式的合併,開始打算利用連結串列本身的空間去做,但考慮到兩個連結串列共享同一個空間,會導致斷鏈,故還是採取了增加空間複雜度
如果資料量小的話,可以先把連結串列轉換成整數,然後相交後再轉換成連結串列的形式
#include <iostream> #include <algorithm> using namespace std; static int debug = 0; struct ListNode{ int val; ListNode *next; ListNode(int x):val(x),next(NULL){} }; ListNode *addTwoNumbers(ListNode *l1, ListNode *l2){ if (l1 == NULL) return l2; if (l2 == NULL) return l1; ListNode *head = NULL; ListNode *l3 = head; int carry = 0; while (l1 != NULL && l2 != NULL) { int sum = l1->val + l2->val + carry; carry = sum/10; sum = sum%10; if (head == NULL) { head = new ListNode(sum); l3 = head; }else{ ListNode *tmp = new ListNode(sum); l3 ->next = tmp; l3 = tmp; } l1 = l1->next; l2 = l2->next; } while (l1!=NULL) { int sum = carry + l1->val; carry = sum/10; sum = sum%10; ListNode *tmp = new ListNode(sum); l3 ->next = tmp; l3 = tmp; l1 = l1->next; } while (l2!=NULL) { int sum = carry + l2->val; carry = sum/10; sum = sum%10; ListNode *tmp = new ListNode(sum); l3 ->next = tmp; l3 = tmp; l2 = l2->next; } if (carry) { ListNode *tmp = new ListNode(carry); l3 ->next = tmp; l3 = tmp; } return head; } int main(){ ListNode *a = new ListNode(5); ListNode *b = new ListNode(5); ListNode *c = addTwoNumbers(a,b); while (c != NULL) { cout<<c->val<<endl; c = c->next; } }