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; } }