2 つの非負の整数を表す 2 つの空ではないリンク リストが与えられます。それぞれの番号は逆順に保存されます 2023-03-01 15:400 read · 0 likes · 0 comments

2 つの非負の整数を表す 2 つの空ではないリンク リストが与えられます。それぞれ逆順に保存されています
2023-03-01 15:400Read・0Like・0Comment

ヨーグルトパーク
ファン数: 1747 記事数: 71
フォロワー
2 つの非負の整数を表す、空ではないリンク リストが 2 つ与えられます。それぞれの数字は逆の順序で保存され、各ノードは 1 つの数字のみを保存できます。

2 つの数値を加算し、その合計を同じ形式で表すリンク リストを返してください。

どちらの数字もゼロ以外のゼロで始まるとは考えられません。

/**

  • 単一リンクリストの定義。

  • パブリック クラス ListNode {

  • int val;
    
  • ListNode next;
    
  • ListNode() {}
    
  • ListNode(int val) { this.val = val; }
    
  • ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    
  • }

*/

クラス ソリューション {

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {



    

    // Initialize variables

    ListNode result = new ListNode(0); // Head node

    ListNode prevNode = result;

    int carry = 0;

    

    while (l1 != null || l2 != null) {

        int x = (l1 != null) ? l1.val : 0;

        int y = (l2 != null) ? l2.val : 0;

        int sum = x + y + carry;

        

        // Update carry

        if (sum > 9) {

            carry = 1;

            sum %= 10;

        } else {

            carry = 0;

        }

        

        // Update the linked list

        ListNode currentNode = new ListNode(sum);

        prevNode.next = currentNode;

        prevNode = currentNode;

        

        // Move to the next nodes of l1 and l2

        if (l1 != null) {

            l1 = l1.next;

        }

        if (l2 != null) {

            l2 = l2.next;

        }

    }



    // Check if there is any carry left

    if (carry != 0) {

        prevNode.next = new ListNode(carry);

    }

    

    // Return the resulting list

    return result.next;

}

}

おすすめ

転載: blog.csdn.net/zezeaichirou/article/details/129283009