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

leetcode_2_题——Add Two Numbers(链表)

时间:2015-05-07 21:59:52      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:

Add Two Numbers

 Total Accepted: 58510 Total Submissions: 268082My Submissions

 

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

 

Hide Tags
 Linked List Math
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

#include<iostream>
using namespace std;
struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};


ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
	ListNode* ptr1=l1;
	ListNode* ptr2=l2;
	ListNode* head=NULL;
	ListNode* ptr;
	int jinwei=0;
	if(ptr1==NULL&&ptr2==NULL)//若都是空的则直接返回
		return head;

	head=(ListNode*)malloc(sizeof(ListNode));
	if(ptr1!=NULL&&ptr2!=NULL)//两个都不为空
	{
		head->val=(ptr1->val+ptr2->val)%10;
		jinwei=(ptr1->val+ptr2->val)/10;
	}
	else if(ptr1==NULL&&ptr2!=NULL)//其中一个为空,也可以直接返回那个不为空的链表即可
		return ptr2;
	else
		return ptr1;

	head->next=NULL;
	ptr=head;

	//下面是两个链表的第一个都不为空
	while(1)
	{
		//这里若有一个为空的话就不再往后移了,
		if(ptr1!=NULL)
			ptr1=ptr1->next;
		if(ptr2!=NULL)
			ptr2=ptr2->next;

		if(ptr1==NULL&&ptr2==NULL)//若两个链表都已经到了最后为空的地方,就可以计算跳出循环了
		{
			if(jinwei==1)
			{
				ListNode* temp2=(ListNode*)malloc(sizeof(ListNode));
				temp2->val=1;
				temp2->next=NULL;
				ptr->next=temp2;
				ptr=temp2;
			}
			break;
		}
		//这里说明肯定最少有一个不是空的,还需要继续计算,继续循环
		int a=0,b=0;
		if(ptr1!=NULL)
			a=ptr1->val;
		if(ptr2!=NULL)
			b=ptr2->val;

		ListNode* temp=(ListNode*)malloc(sizeof(ListNode));
		temp->val=(a+b+jinwei)%10;
		jinwei=(a+b+jinwei)/10;
		temp->next=NULL;
		ptr->next=temp;
		ptr=temp;
	}
	return head;
}
int main()
{
	ListNode* l1=(ListNode*)malloc(sizeof(ListNode));
	l1->next=NULL;
	l1->val=0;
	ListNode* l2=(ListNode*)malloc(sizeof(ListNode));
	l2->val=7;
	l2->next=(ListNode*)malloc(sizeof(ListNode));
	l2->next->val=3;
	l2->next->next=NULL;

	ListNode* l3=addTwoNumbers(l1,l2);
}

  

leetcode_2_题——Add Two Numbers(链表)

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4486062.html

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