LeetCode日记(2)--Add Two Numbers

题目描述:

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

题解:

题目实际上是两个链表的加法操作,有特殊的一点就是,当两个链表的数相加大于10时会产生进位,在下一次相加操作的时候这个进位就要加上去。下图描述了过程。(以342+564=807为例)

LeetCode日记(2)--Add Two Numbers_第1张图片

需要考虑下面三种个情况:

LeetCode日记(2)--Add Two Numbers_第2张图片

算法设计思想:

  • 设置不存放实际值的首节点,设置为0。
  • 设置一个进位变量carry初始化为 0。
  • 遍历两个链表l1和l2
  • 将 x 设为l1遍历结点的值。如果l1已经到达末尾,则将其值设置为 0。
  • 将 y 设为l2遍历结点的值。如果l2已经到达末尾,则将其值设置为 0。
  • 设定 sum = x + y + carry
  • 更新进位的值,carry = sum / 10(sum最大只取到9+9+1=19,所以carry>10时取1,<10时取0)
  • 创建一个数值为 (sum 模10)的新结点,并将其设置为当前结点的下一个结点,然后将当前结点前进到下一个结点。
  • 检查是否 carry = 1,如果成立,即需要进位,则向返回列表追加一个含有数字 1的新结点。
  • 返回首结点的下一个结点。(因为首节点我们不放值,这是为了操作统一,相当于废弃了第一个节点)
     

代码如下:

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    ListNode *dummyHead = new ListNode(0);
    ListNode *curr = dummyHead;
    int carry = 0;
    while (l1||l2 ) {
    	int x,y;
    	if(l1){
    		x=l1->val;
		}else{
			x=0;
		}
		if(l2)
		{
			y=l2->val;
		}else{
			y=0;
		}
        int sum = carry + x + y;
        carry = sum/10;
        curr->next = new ListNode(sum % 10);
        curr = curr->next;
        if (l1!= NULL) l1 = l1->next;
        if (l2!= NULL) l2 = l2->next;
    }
    if (carry > 0) {
        curr->next = new ListNode(carry);
    }
    return dummyHead->next;
    }
};

 

你可能感兴趣的:(leetcode刷题,leetcode,算法,c++)