标签:
//连个链表相加// #include "stdafx.h" #include <iostream> using namespace std; // single linked list node struct listNode{ int val; listNode *next; listNode(int x) :val(x), next(nullptr){} }; listNode *addTwoNumber(listNode *&L1, listNode *&L2) { int value = 0; int carry = 0; listNode headNode(-1); listNode *pre = &headNode; for (listNode *pa = L1, *pb = L2; pa != nullptr || pb != nullptr; pa = pa == nullptr ? nullptr : pa->next, pb = pb == nullptr ? nullptr : pb->next) { value = (pa->val + pb->val + carry) % 10; carry = (pa->val + pb->val + carry) / 10; pre->next = new listNode(value); pre = pre->next; } if (carry > 0) pre->next = new listNode(carry); return headNode.next; } int _tmain(int argc, _TCHAR* argv[]) { listNode *L1; L1 = new listNode(2); L1->next = new listNode(4); L1->next->next = new listNode(3); listNode *L2; L2 = new listNode(5); L2->next = new listNode(6); L2->next->next = new listNode(7); listNode *L3 = addTwoNumber(L1, L2); cout << L3->val << L3->next->val << L3->next->next->val << L3->next->next->next->val << endl; system("pause"); return 0; }
标签:
原文地址:http://www.cnblogs.com/wxquare/p/4520801.html