2022/12/21

LeetCode 2. Add Two Numbers

問題:將兩個鏈結陣列做相加並輸出相加後的鏈結,注意進位問題
解法:這題就是鏈結走訪而已,不過要注意要將進位問題放進while去判斷,數值相加後要記得去給予是否有進位需求
 C#
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
public class Solution {
    public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
    {
        ListNode headNode = null;
        ListNode nextNode = null;
        int v = 0;
        int carry = 0;
        while (l1 != null || l2 != null || carry == 1)
        {
            if (l1 != null && l2 != null)
            {
                v += l1.val + l2.val;
                l1 = l1.next;
                l2 = l2.next;
            }
            else if (l1 != null)
            {
                v += l1.val;
                l1 = l1.next;
            }
            else if (l2 != null)
            {
                v += l2.val;
                l2 = l2.next;
            }

            carry = v >= 10 ? 1 : 0;

            ListNode node = new ListNode(v % 10);
            if (headNode == null)
            {
                headNode = node;
            }
            else
            {
                nextNode.next = node;
            }
            v /= 10;
            nextNode = node;
        }

        return headNode;
    }
}