LeetCode: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.

思路

直接通过对指针操作求和即可,注意进位。主要处理分三个阶段:
1.两个链表都没到尾节点时,对两个链表的节点值相加并加上进位,记录进位。
2.当一个链表达到尾节点时,对没达到尾节点的链表和进位值进行相加,记录进位。
3.两个链表都达到尾节点时,将进位加入链表。

代码

/**
 * 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) {
        int t=0;
        ListNode* temp1=l1;
        ListNode* temp2=l2;
        ListNode* head=(ListNode*)malloc(sizeof(ListNode));
        ListNode* temp=head;
        while(temp1!=NULL&&temp2!=NULL)
        {
            ListNode* addNode=(ListNode*)malloc(sizeof(ListNode));
            int n=temp1->val+temp2->val;
            addNode->val=(n+t)%10;
            t=(n+t)/10;
            temp->next=addNode;
            temp=temp->next;
            temp1=temp1->next;
            temp2=temp2->next;
        }

        if(temp1||temp2)
        {
            if(temp1==NULL)
            {
                temp1=temp2;
            }
            while(temp1!=NULL)
            {
                ListNode* addNode=(ListNode*)malloc(sizeof(ListNode));
                addNode->val=(temp1->val+t)%10;
                t=(temp1->val+t)/10;
                temp->next=addNode;
                temp=temp->next;
                temp1=temp1->next;
            }
        }   

        if(t)
        {
            ListNode* addNode=(ListNode*)malloc(sizeof(ListNode));
            addNode->val=t;
            temp->next=addNode;
            temp=temp->next;
        }

        temp->next=NULL;
        return head->next;
    }
};

你可能感兴趣的:(刷题,刷题笔记)