【LeetCode-面試演算法經典-Java實現】【002-Add Two Numbers (單鏈表表示的兩個數相加)】,leetcode--java

來源:互聯網
上載者:User

【LeetCode-面試演算法經典-Java實現】【002-Add Two Numbers (單鏈表表示的兩個數相加)】,leetcode--java
【002-Add Two Numbers (單鏈表表示的兩個數相加)】原題

  You are given two linked lists representing two non-negative numbers. 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.
  Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
  Output: 7 -> 0 -> 8

題目大意

  有兩個單鏈表,代表兩個非負數,每一個節點代表一個數位,數字是反向儲存的,即第一個結點表示最低位,最後一個結點表示最高位。求兩個數的相加和,並且以鏈表形式返回。

解題思路

  對兩個鏈表都從第一個開始處理,進行相加,結果再除以10求商,作為下一位相加的進位,同時記錄餘數,作為本位的結果,一直處理,直到所有的結點都處理完。

代碼實現
 /**     * 002-Add Two Numbers (單鏈表表示的兩個數相加)     * @param l1 第一個數     * @param l2 第二個數     * @return 結果     */    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {        if (l1 == null) {            return l2;        }        if (l2 == null) {            return l1;        }        ListNode p1 = l1;        ListNode p2 = l2;        ListNode root = new ListNode(0); // 頭結點        ListNode r = root;        root.next = l1;        int carry = 0; // 初始進位        int sum;        while (p1 != null && p2 != null) {            sum = p1.val + p2.val + carry;            p1.val = sum % 10; // 本位的結果            carry = sum / 10; // 本次進位            r.next = p1;            r = p1; // 指向最後一個相加的結點            p1 = p1.next;            p2 = p2.next;        }        if (p1 == null) {            r.next = p2;        } else {            r.next = p1;        }        // 最後一次相加還有進位        if (carry == 1) {            // 開始時r.next是第一個要相加的結點            while (r.next != null) {                sum = r.next.val + carry;                r.next.val = sum % 10;                carry = sum / 10;                r = r.next;            }            // 都加完了還有進位,就要建立一個新的結點            if (carry == 1) {                r.next = new ListNode(1);            }        }        return root.next;    }}
評測結果

  點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。

特別說明歡迎轉載,轉載請註明出處【http://blog.csdn.net/DERRANTCM/article/details/46905467】

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.