首页 > 其他 > 详细

leetcode2 add two numbers

时间:2018-09-23 14:14:19      阅读:115      评论:0      收藏:0      [点我收藏+]

一开始本想用函数把两个链表代表的数字都加起来,然后再取每一位数字合成链表,结果发现因为数字位数太多类似大整数,无法直接求出和,所以必须每一位都相加然后组成链表。

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
	ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
		ListNode* s;
		s = NULL;
		ListNode* curs;
		int sum = 0;
		while (l1 != NULL || l2 != NULL)
		{
			if (l1 != NULL)
			{
				sum += l1->val;
				l1 = l1->next;
			}
			if (l2 != NULL)
			{
				sum += l2->val;
				l2 = l2->next;
			}
			if (s == NULL)
			{
				s = new ListNode(sum % 10);
				curs = s;
			}
			else
			{
				curs->next = new ListNode(sum % 10);
				curs = curs->next;
			}
			sum /= 10;
		}
		if (sum == 1)
		{
			curs->next = new ListNode(1);
		}
		return s;
	}
};

  

leetcode2 add two numbers

原文:https://www.cnblogs.com/legendcong/p/9692430.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!