LeetCode 2. Add Two Numbers(鏈表題目)

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.

思路分析

這個題其實沒有什麼特別,對應的鏈表結點進行加法運算就行,只不過需要進行記錄有無進位。存在一個新的鏈表裏面就可以,這就需要開闢新空間(new操作),如果鏈表爲空,則認爲結點中的值爲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) {
        
        if(l1==NULL&&l2==NULL)
            return NULL;
        
        //注意進位應該就行
        ListNode* dumy=new ListNode(0);
        ListNode* p=dumy;
        int flag=0;  //進位標誌
        
        while(l1||l2||flag)
        {
            int sum=(l1!=NULL?l1->val:0)+(l2!=NULL?l2->val:0)+flag;
            flag=sum/10;
            p->next=new ListNode(sum%10);
            p=p->next;
            
            l1 = (l1!=NULL) ? l1->next : l1;
            l2 = (l2!=NULL) ? l2->next : l2;               
        }
        
        return dumy->next;

    }
};




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章