leetcode2 add two numbers

一开始本想用函数把两个链表代表的数字都加起来,然后再取每一位数字合成链表,结果发现因为数字位数太多类似大整数,无法直接求出和,所以必须每一位都相加然后组成链表。学到了处理进位的方法,十分优雅,每次很自然的/10,大于10的话sum值自动变为1,如果最后还是1的话就再开一个结点来扩展一位

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

  

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