标签:des blog io os ar strong sp div c
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
代码:
// AddTwoNumbers.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #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 *res,*p; int plus = 0,sum=0; res = new ListNode(0); p = res; while (l1 != NULL&&l2 != NULL) { sum = l1->val + l2->val+plus; //p = new ListNode(sum % 10); p->val = sum % 10; plus = sum / 10; l1 = l1->next; l2 = l2->next; if (l1 != NULL&&l2 != NULL) { ListNode *temp = new ListNode(0); p->next = temp; p = p->next; } } if (l1 == NULL&&l2 == NULL) { if (plus != 0) { ListNode *temp = new ListNode(plus); p->next = temp; p = p->next; } } else if (l1 == NULL) { while (l2 != NULL) { sum =l2->val + plus; ListNode *temp = new ListNode(sum % 10); plus = sum / 10; p->next = temp; p = p->next; l2 = l2->next; } if (plus != 0) { ListNode *temp = new ListNode(plus); p->next = temp; p = p->next; } } else if (l2 == NULL) { while (l1 != NULL) { sum = l1->val + plus; ListNode *temp = new ListNode(sum % 10); plus = sum / 10; p->next = temp; p = p->next; l1 = l1->next; } if (plus != 0) { ListNode *temp = new ListNode(plus); p->next = temp; p = p->next; } } return res; } }; int _tmain(int argc, _TCHAR* argv[]) { ListNode *l1 = new ListNode(1); //ListNode *l2 = new ListNode(4); //ListNode *l3 = new ListNode(3); //l1->next = l2; //l2->next = l3; ListNode *ll1 = new ListNode(9); ListNode *ll2 = new ListNode(9); //ListNode *ll3 = new ListNode(4); ll1->next = ll2; //ll2->next = ll3; Solution ss; ListNode *res = ss.addTwoNumbers(l1,ll1); while (res != NULL) { cout << res->val << ""; res = res->next; } system("pause"); return 0; }
标签:des blog io os ar strong sp div c
原文地址:http://www.cnblogs.com/supernigel/p/4003743.html