码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Add Two Numbers

时间:2015-02-02 23:06:26      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:大整数求和   链表   无头结点   

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;
}




[LeetCode]Add Two Numbers

标签:大整数求和   链表   无头结点   

原文地址:http://blog.csdn.net/kaitankedemao/article/details/43418603

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!