2. 自我刷題之兩數相加

回歸次數:1

題目:

著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處
給出兩個 非空 的鏈表用來表示兩個非負的整數。其中,它們各自的位數是按照 逆序 的方式存儲的,并且它們的每個節點只能存儲 一位 數字。

如果,我們將這兩個數相加起來,則會返回一個新的鏈表來表示它們的和。

您可以假設除了數字 0 之外,這兩個數都不會以 0 開頭。

示例:


輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807

解答:


class ListNode {
      int val;
      ListNode next;
      ListNode(int x) { val = x; }
  }



  public class Test2 {

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {


        ListNode dummyHead = new ListNode(0);
        ListNode p = l1;
        ListNode q = l2;
        ListNode cur = dummyHead;
        int carry = 0;
        while (p !=null || q != null){

            //拿到數據
            int x = p != null ? p.val : 0;
            int y = q != null ? q.val : 0;

            //計算是否有余數
            int sum = carry + x + y;
            carry = sum / 10;

            //賦予新的鏈表
            cur.next = new ListNode(sum % 10);
            //保證cur始終是鏈表的最后一位
            cur = cur.next;
            if (p != null) p = p.next;
            if (q != null) q = q.next;
        }

        //判斷最后一位是否有余數
        if (carry != 0){
            cur.next = new ListNode(carry);
        }
        //返回去除頭部為0的鏈表
        return  dummyHead.next;
    }


      /**
       * 遍歷
       * @param l
       */
    public static void tranNode(ListNode l){

        while (l!= null){

            System.out.println(l.val);
            l = l.next;
        }
        System.out.println("\n");
    }


      public static void main(String[] args) {

        //創建初始鏈表
        ListNode l1 = new ListNode(2);
        ListNode cur1 = l1;
          cur1.next = new ListNode(4);
          cur1 = cur1.next;
          cur1.next = new ListNode(3);

        ListNode l2 = new ListNode(5);
          ListNode cur2 = l2;
          cur2.next = new ListNode(6);
          cur2 = cur2.next;
          cur2.next = new ListNode(4);

          Test2.tranNode(l1);

          Test2.tranNode(l2);

          ListNode result = Test2.addTwoNumbers(l1,l2);
          Test2.tranNode(result);
      }
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。