【递归应用】有序链表的合并

 题:已知两个链表head1和head2各自有序,请把它们合并成一个依然有序的链表。结果链表要包含head1和head2的所有结点,即结点值相同。

package exam2;

public class MergeList {

    // 节点内部类定义.
    static class Node {
        Node next; // 单向列表.
        int data;  // 节点值.

        public Node(int data) {
            this.data = data;
        }

        public int getData() {
            return data;
        }

        public void setNext(Node next) {
            this.next = next;
        }
    }

    public static Node mergeList(Node head1, Node head2) {
        if(head1 == null) {
            return head2;
        }
        if(head2 == null) {
            return head1;
        }
        Node head = null;
        if(head1.getData() < head2.getData()) {
            head = head1;
            head.setNext(mergeList(head1.next, head2));
        }
        else {
            head = head2;
            head.setNext(mergeList(head1, head2.next));
        }
        return head;
    }

    public static void main(String[] args) {
        Node head1 = new Node(1);
        Node node2 = new Node(3);
        Node node3 = new Node(5);
        Node node4 = new Node(7);
        Node node5 = new Node(9);

        head1.setNext(node2);
        node2.setNext(node3);
        node3.setNext(node4);
        node4.setNext(node5);
        node5.setNext(null);

        Node head2 = new Node(2);
        Node node22 = new Node(4);
        Node node23 = new Node(6);
        Node node24 = new Node(8);
        Node node25 = new Node(10);

        head2.setNext(node22);
        node22.setNext(node23);
        node23.setNext(node24);
        node24.setNext(node25);
        node25.setNext(null);

        Node mergeHeader = mergeList(head1, head2);
        Node indexHeader = mergeHeader;
        if(indexHeader != null) {

            while (indexHeader.next != null) {
                int data = indexHeader.getData();
                System.out.print( indexHeader.getData() + " ");
                indexHeader = indexHeader.next;
            }
            System.out.print( indexHeader.getData() + " ");
        }
    }




}
View Code

 

posted @ 2022-04-07 17:16  v大喵  阅读(28)  评论(0编辑  收藏  举报