Java資料結構與演算法面試題-兩數之和 作者:哇塞大嘴好帥

哇塞大嘴好帥發表於2020-11-27

Java資料結構與演算法面試題-兩數之和 作者:哇塞大嘴好帥

作者:哇塞大嘴好帥

​ 哇塞大嘴好帥

1.題目 -該題目由LeetCode提供

ou are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example 1:

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/add-two-numbers
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

2.完整程式碼

package com.dazuizui.兩數相加;


/**
 * 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 contains a single digit. Add the two numbers and return the sum as a linked list.
 *
 * You may assume the two numbers do not contain any leading zero, except the number 0 itself.
 *
 * 來源:力扣(LeetCode)
 * 連結:https://leetcode-cn.com/problems/two-sum
 * 著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
 * @author Yida·Yang
 * @Time   2020-11-25
 * @Text   連結串列管理
 */
public class Demo1 {
    public static void main(String[] args) {
        NodeAdmin nodeAdmin = new NodeAdmin();
        nodeAdmin.addNode(1);
        nodeAdmin.addNode(2);
        nodeAdmin.addNode(4);
        nodeAdmin.addNode(5);

        NodeAdmin nodeAdmin1 = new NodeAdmin();
        nodeAdmin1.addNode(1);
        nodeAdmin1.addNode(2);
        nodeAdmin1.addNode(4);
        nodeAdmin1.addNode(5);
        nodeAdmin1.selectLinkenList();

        Solution solution = new Solution();
        ListNode listNode = solution.addTwoNumbers(nodeAdmin.getHead(), nodeAdmin1.getHead());

    }
}

/**
 * 面試題 兩數相加
 * @author Yida·Yang
 * @Time   2020-11-25
 * @Text   兩數相加
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //建立頭節點,尾巴節點
        ListNode head = null,foot = null;
        //進位
        int carry = 0;
        //和
        int sum = 0;

        //兩數相加操作
        while(true){
            int num1 = l1 != null ? l1.val : 0;
            int num2 = l2 != null ? l2.val : 0;
            sum = num1 + num2 +carry;

            if(head == null){
                head = foot = new ListNode(sum % 10);
            }else {
                foot.next = new ListNode(sum % 10);
                foot = foot.next;
                System.out.println("sum:"+sum+" foot = "+foot.val);
            }

            carry = sum / 10;

            //指標下移動
            if (l1 != null){
                l1 = l1.next;
            }

            if (l2 != null){
                l2 = l2.next;
            }

            if(l2 == null && l1 == null){
                break;
            }

        }

        if (carry > 0){
            foot.next = new ListNode(carry) ;
            System.out.println(foot.next.val);
        }

        return head;
    }
}


/**
 * @author Yida·Yang
 * @Time   2020-11-25
 * @Text   連結串列管理
 */
class NodeAdmin{
    ListNode head = new ListNode();

    //獲取當前節點
    public ListNode getHead(){
        return this.head;
    }

    //新增一個連結串列
    public void addNode(int val) {
        //建立臨時遍歷
        ListNode temp = head;

        //如果頭節點為NULL
        while (true){
            if(temp.next == null){
                break;
            }

            temp = temp.next;
        }
        temp.next = new ListNode(val);
        System.out.println("新增temp:"+temp);
    }

    //瀏覽連結串列
    public void selectLinkenList(){
        //建立臨時遍歷
        ListNode temp = head.next;

        while (true){
            if (temp == null){
                break;
            }


            System.out.println(temp.val);
            temp = temp.next;
        }
    }
}


/**
 * @author Yida·Yang
 * @Time   2020-11-25
 * @Text   連結串列節點
 */
class ListNode {
    int val;
    ListNode next;
    ListNode() {}

    @Override
    public String toString() {
        return "ListNode{" +
                "val=" + val +
                ", next=" + next +
                '}';
    }

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

3.程式碼解析

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 * @author  哇塞大嘴好帥
 * @blogurl www.dazuizui.com
 * @e-mail  y51288033@outlook.com
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //建立頭節點,尾節點。
        ListNode head = null,foot = null;

        //進位
        int carry = 0;
        //和
        int sum   = 0;

        //兩數相加操作
        while(true){
            int num1 = l1 != null ? l1.val : 0;
            int num2 = l2 != null ? l2.val : 0;
            sum = num1 + num2 + carry;

            //計算
            if(head == null){
                head = foot = new ListNode(sum % 10);
            }else{
                foot.next = new ListNode(sum % 10);
                foot = foot.next;
            }

            //計算進位數
            carry = sum / 10;

            //尾指標下移
            if(l1 != null){
                l1 = l1.next;
            }

            if(l2 != null){
                l2 = l2.next;
            }

            //如果其中有一者為NULL則跳出迴圈
            if(l1 == null && l2 == null){
                break;
            }
        }

        if(carry > 0){
            foot.next = new ListNode(carry);
        }

        return head;
    }
}

​ 首先定義頭節點,還有臨時變數(臨時變數要永遠指向最後一個節點),之後在定義兩個遍歷一個和一個進位,之後進入while迴圈 如果head == null 成立就代表是第一個節點,如果是第一個節點就把頭和尾節點都賦值為sum % 10,如果不是第一個節點就臨時變數的下一個節點 = new ListNode(sum % 10); 然後指標下移,之後就是指標下移判斷,如果兩者連結串列(l1 and l2)都為null 那麼就代表兩數相加操作已經做完了就跳出迴圈,跳出迴圈後判斷是否有進位,如果有進位,就尾節點的下一個**= new ListNode(carry);** 之後返回頭節點。

相關文章