设为首页 加入收藏

TOP

leetcode_2_Add Two Numbers
2015-07-20 17:16:23 来源: 作者: 【 】 浏览:2
Tags:leetcode_2_Add Two Numbers

?

?

Add Two Numbers
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

?

?

class Solution {
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        if(l1==NULL && l2==NULL)
			return NULL;
		if (l1==NULL)
			return l2;
		if (l2==NULL)
			return l1;

		ListNode *head = NULL , *pre = NULL;
		int c=0;

		while( l1!=NULL || l2!=NULL || c!=0 )
		{
			if(l1!=NULL)
			{
				c += l1->val;
				l1 = l1->next;
			}
			if(l2!=NULL)
			{
				c += l2->val;
				l2 = l2->next;
			}
			ListNode *p = new ListNode(c%10);
			if(head == NULL)
				head = p;
			else
				pre->next = p;
			pre = p;
			c /= 10;
		}
		return head;
    }
};


?

?

#include
  
   

using namespace std;

#define N 3

struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        if(l1==NULL && l2==NULL)
			return NULL;
		if (l1==NULL)
			return l2;
		if (l2==NULL)
			return l1;

		ListNode *head = NULL , *pre = NULL;
		int c=0;

		while( l1!=NULL || l2!=NULL || c!=0 )
		{
			if(l1!=NULL)
			{
				c += l1->val;
				l1 = l1->next;
			}
			if(l2!=NULL)
			{
				c += l2->val;
				l2 = l2->next;
			}
			ListNode *p = new ListNode(c%10);
			if(head == NULL)
				head = p;
			else
				pre->next = p;
			pre = p;
			c /= 10;
		}
		return head;
    }
};

ListNode *creatlist()
{
	ListNode *head=NULL;
	for(int i=0; i
   
    >a; ListNode *p; p = (ListNode*)malloc(sizeof(ListNode)); p->val = a; p->next = head; head = p; } return head; } int main() { ListNode *list1 = creatlist(); ListNode *list2 = creatlist(); Solution lin; ListNode *outlist = lin.addTwoNumbers( list1,list2 ); for(int i=0; i
    
     val; outlist = outlist->next; } }
    
   
  


?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇leetcode_148_Sort List 下一篇Codeforces Round #293 (Div. 2) ..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·怎样用 Python 写一 (2025-12-27 02:49:19)
·如何学习python数据 (2025-12-27 02:49:16)
·想要自学数据分析, (2025-12-27 02:49:14)
·Java 集合框架 - 菜 (2025-12-27 02:19:36)
·Java集合框架最全详 (2025-12-27 02:19:33)