1. 程式人生 > >java實現兩個有序單鏈表合併

java實現兩個有序單鏈表合併

本次分享的事兩個有序單鏈表的合併,

遍歷方法

  • 遞迴

  • 非遞迴

節點類

/**
 * @auther: lawt
 * @date: 2018/11/4 08
 * @Description: 結點資訊
 */
public class Node {
    /**
     * 為了方便,這兩個變數都使用public,而不用private就不需要編寫get、set方法了。
     * 存放資料的變數,簡單點,直接為int型
     */
    public int data;
    /**
     * 存放結點的變數,預設為null
     */
    public Node next;

    /**
     * 構造方法,在構造時就能夠給data賦值
     */
    public Node(int data) {
        this.data = data;
    }
}

實現類

/**
 * @auther: lawt
 * @date: 2018/11/6 09
 * @Description: 兩個有序單鏈表合併
 */
public class MyList {
    /**
     * 遞迴方式合併兩個單鏈表
     *
     * @param head1 有序連結串列1
     * @param head2 有序連結串列2
     * @return 合併後的連結串列
     */
    public static Node mergeTwoList(Node head1, Node head2) {
        //遞迴結束條件
        if (head1 == null && head2 == null) {
            return null;
        }
        if (head1 == null) {
            return head2;
        }
        if (head2 == null) {
            return head1;
        }
        //合併後的連結串列
        Node head = null;
        if (head1.data > head2.data) {
            //把head較小的結點給頭結點
            head = head2;
            //繼續遞迴head2
            head.next = mergeTwoList(head1, head2.next);
        } else {
            head = head1;
            head.next = mergeTwoList(head1.next, head2);
        }
        return head;
    }

    /**
     * 非遞迴方式
     *
     * @param head1 有序單鏈表1
     * @param head2 有序單鏈表2
     * @return 合併後的單鏈表
     */
    public static Node mergeTwoList2(Node head1, Node head2) {
        if (head1 == null || head2 == null) {
            return head1 != null ? head1 : head2;
        }
        //合併後單鏈表頭結點
        Node head = head1.data < head2.data ? head1 : head2;

        Node cur1 = head == head1 ? head1 : head2;
        Node cur2 = head == head1 ? head2 : head1;

        Node pre = null;//cur1前一個元素
        Node next = null;//cur2的後一個元素

        while (cur1 != null && cur2 != null) {
            //第一次進來肯定走這裡
            if (cur1.data <= cur2.data) {
                pre = cur1;
                cur1 = cur1.next;
            } else {
                next = cur2.next;
                pre.next = cur2;
                cur2.next = cur1;
                pre = cur2;
                cur2 = next;
            }
        }
        pre.next = cur1 == null ? cur2 : cur1;
        return head;
    }

    public static void main(String[] args) {
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        Node node5 = new Node(5);

        node1.next = node3;
        node3.next = node5;
        node2.next = node4;
//        Node node = mergeTwoList(node1, node2);
        Node node = mergeTwoList2(node2, node1);
        while (node != null) {
            System.out.print(node.data + " ");
            node = node.next;
        }
    }
}

執行結果