Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // leetcode-002.cpp : 定義主控台應用程式的進入點。
- //
- #include "stdafx.h"
- #include <iostream>
- #include <stdlib.h> /* 亂數相關函數 */
- #include <time.h>
- using namespace std;
- struct ListNode {
- int val;
- ListNode *next;
- ListNode(int x) : val(x), next(NULL) {}
- };
- void print(ListNode* pos)
- {
- //pos = pos->next;
- while (pos!= NULL)
- {
- cout << pos->val << " -> ";
- pos = pos->next;
- }
- cout << endl;
- return;
- }
- class Solution {
- public:
- ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
- ListNode *l1pos = l1,*l2pos=l2;
- ListNode *head = new ListNode(0);
- ListNode *nowpos = head;
- while (l1pos != NULL || l2pos != NULL)
- {
- if (l1pos == NULL)
- {
- nowpos->next = new ListNode(l2pos->val);
- l2pos = l2pos->next;
- nowpos = nowpos->next;
- }
- else if (l2pos == NULL)
- {
- nowpos->next = new ListNode(l1pos->val);
- l1pos = l1pos->next;
- nowpos = nowpos->next;
- }
- else
- {
- nowpos->next = new ListNode(l1pos->val + l2pos->val);
- l1pos = l1pos->next;
- l2pos = l2pos->next;
- nowpos = nowpos->next;
- }
- }
- nowpos = head;
- while (nowpos != NULL)
- {
- if (nowpos->val >= 10)
- {
- if (nowpos->next != NULL)
- {
- nowpos->next->val += nowpos->val / 10;
- }
- else
- {
- nowpos->next = new ListNode(nowpos->val / 10);
- }
- }
- nowpos->val %= 10;
- nowpos = nowpos->next;
- }
- return head->next;
- }
- };
- void make(ListNode *test)
- {
- srand(time(NULL));
- for (int i = 0; i < (rand() / (RAND_MAX + 1.0) * 10)+5; i++)
- {
- int x = rand() / (RAND_MAX + 1.0) * 10;
- test->next = new ListNode(x);
- cout << test<<' ' << x << ' ' << test->next << endl;
- test = test->next;
- }
- cout << endl;
- }
- int main()
- {
- ListNode *test1 = new ListNode(0), *test2 = new ListNode(0);
- make(test1);
- make(test2);
- system("PAUSE");
- cout << "test1:\n";
- print(test1);
- cout << "test2:\n";
- print(test2);
- Solution sol;
- cout << "add:\n";
- print(sol.addTwoNumbers(test1, test2));
- return 0;
- }
Add Comment
Please, Sign In to add comment