#include<iostream> #include<queue> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { if (l1 == NULL) return l2; if (l2 == NULL) return l1; queue<int> que1; queue<int> que2; while (l1){ que1.push(l1->val); l1 = l1->next; } while (l2){ que2.push(l2->val); l2 = l2->next; } int carry = 0;//进位标志 int sum = que1.front() + que2.front();//从最低位开始加 que1.pop(); que2.pop(); if (sum > 9){ carry = 1; sum %= 10; } ListNode* head = new ListNode(sum); ListNode* cur = head; ListNode* temp = NULL; while (!que1.empty()&&!que2.empty()){//从最低位开始加 sum =carry+ que1.front() + que2.front(); que1.pop(); que2.pop(); if (sum > 9){ carry = 1; sum %= 10; }else carry = 0; temp = new ListNode(sum); cur->next = temp; cur = temp; } while (!que1.empty()){ sum = carry + que1.front(); que1.pop(); if (sum > 9){ carry = 1; sum %= 10; } else carry = 0; temp = new ListNode(sum); cur->next = temp; cur = temp; } while (!que2.empty()){ sum = carry + que2.front(); que2.pop(); if (sum > 9){ carry = 1; sum %= 10; } else carry = 0; temp = new ListNode(sum); cur->next = temp; cur = temp; } if (carry){ //最后有进位别忘 temp = new ListNode(carry); cur->next = temp; cur = temp; } return head; } ListNode* createList(ListNode* head){ int numOfNode; int value; cout << "please input number of listNode:"; cin >> numOfNode; cin >> value; head = new ListNode(value); ListNode* cur = head; for (int i = 1; i < numOfNode; ++i){ cin >> value; ListNode* temp = new ListNode(value); cur->next = temp; cur = temp; } return head; } void printNode(ListNode* head){ ListNode* cur = head; while (cur){ cout << cur->val << " "; cur = cur->next; } cout << endl; } }; int main(){ ListNode* head1 = NULL; ListNode* head2 = NULL; Solution solution; head1 = solution.createList(head1); solution.printNode(head1); head2 = solution.createList(head2); solution.printNode(head2); head1 = solution.addTwoNumbers(head1, head2); solution.printNode(head1); system("pause"); return 0; }