1. 程式人生 > >Leetcode# 2. Add Two Numbers(連結串列模擬大數演算法)

Leetcode# 2. Add Two Numbers(連結串列模擬大數演算法)

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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

題意

給定兩個非空的連結串列,表示兩個非負整數。數字以相反的順序儲存,每一個節點包含一個數字。將兩個數相加並將結果作為連結串列返回。
注意返回的結果的列表也是相反的。
運算過程:

2 4 3
5 6 4
—————
7 0 8

特別像字串求大數演算法,這裡題目已經把字串翻轉,簡單了不少。

解決方法一:C++版

思路很簡單,麻煩之處在於指標的使用。sum指向頭結點,,temp代表移動的指標,在末尾新增元素的操作為:
temp ->next = 當前數
指標後移:
temp ->next = next

/**
 * 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 carry = 0;//進位
        ListNode *sum = NULL, *
temp = NULL; while(l1 != NULL || l2 != NULL || carry != 0) { int now = 0;//當前位數 if(l1!=NULL) { now += l1 -> val; l1 = l1 -> next; } if(l2!=NULL) { now += l2 -> val; l2 = l2 -> next; } if(carry != 0) now += carry; carry = now / 10; now = now % 10; //將int型的now轉換為ListNode注意看上面的建構函式要傳引數的 ListNode *p = new ListNode(now); //頭指標指向temp if(sum == NULL) { temp = p; sum = temp; } else { temp -> next = p; temp = temp -> next; } } return sum; } };

解決方法二:Python版

解法思路同上。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        sum = None
        temp = None
        carry = 0
        while l1 != None or l2 != None or carry != 0:
            now = 0
            if l1 != None:
                now = now + l1.val
                l1 = l1.next
            if l2 != None:
                now = now + l2.val
                l2 = l2.next
            if carry != 0:
                now = now + carry
            carry = now / 10
            now = now % 10
            q = ListNode(now)
            if sum == None:
                temp = q
                sum = temp
            else:
                temp.next = q
                temp = temp.next

        return sum

總結