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

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

    private static Node mergeLists(Node L1, Node L2) {
    
        Node P1 = L1.val < L2.val ? L1 : L2;
        Node P2 = L1.val < L2.val ? L2 : L1;
        Node BigListHead = P1;
        Node tempNode = null;
    
        while (P1 != null && P2 != null) {
            if (P1.next != null && P1.next.val >P2.val) {
            tempNode = P1.next;
            P1.next = P2;
            P1 = P2;
            P2 = tempNode;
            } else if(P1.next != null) 
            P1 = P1.next;
            else {
            P1.next = P2;
            break;
            }
        }
    
        return BigListHead;
    }
    

提交回复
热议问题