Q:
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
以前写过大整数求和,不过是用数组实现的,这里要求用链表(无头结点),思路是一样的,我就不再叙述了,贴上链接:点击打开链接
in addition,添上链表的创建便于测试,贴代码:
#include <iostream> 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) { ListNode* p1 = l1; ListNode* p2 = l2; ListNode* l3 = NULL; ListNode* node =NULL; ListNode* r = l3; int flag = 0; int sum = 0; while (p1!=NULL&&p2!=NULL){ sum = (p1->val + p2->val + flag) % 10; flag = (p1->val + p2->val + flag) / 10; node = new ListNode(sum); if (l3 == NULL){ l3 = node; } else{ r->next = node; } r = node; p1 = p1->next; p2 = p2->next; } while (p1 != NULL){ sum = (p1->val + flag) % 10; flag = (p1->val + flag) / 10; node = new ListNode(sum); r->next = node; r = node; p1 = p1->next; } while (p2 != NULL){ sum = (p2->val + flag) % 10; flag = (p2->val + flag) / 10; node = new ListNode(sum); r->next = node; r = node; p2 = p2->next; } if (flag == 1){ node = new ListNode(1); r->next = node; r = node; } return l3; } ListNode* createList(){ ListNode* head = NULL; ListNode* rear = head;; ListNode* p = NULL; int x; while (cin >> x){ p = new ListNode(x); if (head == NULL) head = p; else rear->next = p; rear = p; } cin.clear(); return head; } }; int main() { Solution s; ListNode* l1 = s.createList(); ListNode* l2 = s.createList(); ListNode* l3 = s.addTwoNumbers(l1, l2); ListNode* l = l3; while (l != NULL){ printf("%d ", l->val); l = l->next; } printf("\n"); return 0; }
原文地址:http://blog.csdn.net/kaitankedemao/article/details/43418603