Interview Question: Merge two sorted singly linked lists without creating new nodes

后端 未结 26 2941
有刺的猬
有刺的猬 2020-12-02 04:09

This is a programming question asked during a written test for an interview. \"You have two singly linked lists that are already sorted, you have to merge them and return a

26条回答
  •  失恋的感觉
    2020-12-02 04:13

    Node mergeList(Node h1, Node h2) {
        if (h1 == null) return h2;
        if (h2 == null) return h1;
        Node head;
        if (h1.data < h2.data) {
            head = h1;
        } else {
            head = h2;
            h2 = h1;
            h1 = head;
        }
    
        while (h1.next != null && h2 != null) {
            if (h1.next.data < h2.data) {
                h1 = h1.next;
            } else {
                Node afterh2 = h2.next;
                Node afterh1 = h1.next;
                h1.next = h2;
                h2.next = afterh1;
    
                if (h2.next != null) {
                    h2 = afterh2;
                }
            }
        }
        return head;
    }
    

提交回复
热议问题