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

后端 未结 26 3031
有刺的猬
有刺的猬 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:27

    public static Node merge(Node h1, Node h2) {
    
        Node h3 = new Node(0);
        Node current = h3;
    
        boolean isH1Left = false;
        boolean isH2Left = false;
    
        while (h1 != null || h2 != null) {
            if (h1.data <= h2.data) {
                current.next = h1;
                h1 = h1.next;
            } else {
                current.next = h2;
                h2 = h2.next;
            }
            current = current.next;
    
            if (h2 == null && h1 != null) {
                isH1Left = true;
                break;
            }
    
            if (h1 == null && h2 != null) {
                isH2Left = true;
                break;
            }
        }
    
        if (isH1Left) {
            while (h1 != null) {
                current.next = h1;
                current = current.next;
                h1 = h1.next;
            }
        } 
    
        if (isH2Left) {
            while (h2 != null) {
                current.next = h2;
                current = current.next;
                h2 = h2.next;
            }
        }
    
        h3 = h3.next;
    
        return h3;
    }
    

提交回复
热议问题