The first level of Algorithm Clearance Village - Linked List Silver Challenge Notes

Merge ordered lists

Question description

  1. The idea of ​​merging two ordered lists

    : create a new linked list, loop node1 and node1, compare the values ​​corresponding to different linked lists, point the next of the new linked list to the linked list with the smaller value, and then point the next of the smaller value to its own next, and so on. , until a linked list is traversed with no elements, and then the next of the new linked list points to the remaining linked list.

Code

    public static Node mergeTwoNodeList(Node node1, Node node2) {
    
    
        Node prehead = new Node(0);
        Node prev = prehead;
        while (node1 != null && node2 != null) {
    
    
            if (node1.val >= node2.val) {
    
    
                prev.next = node2;
                node2 = node2.next;
            } else {
    
    
                prev.next = node1;
                node1 = node1.next;
            }
            prev = prev.next;
        }
        prev.next = node1 == null ? node2 : node1;
    }
  1. Merge k elements
public Node mergeKNode(Node[] nodes){
    
    
	Node res=null;
	for(Node node: nodes){
    
    
	  res = mergeTwoNodeList(res,node);
   }
   return res;
}

  1. LeetCode1669: Give you two linked lists list1 and list2, which contain n and m elements respectively. Please delete the nodes with subscripts from a to b in list1, and connect list2 to the position of the deleted node.
    public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
    
    
        ListNode pre1 = list1, post1 = list1, post2 = list2;
        int i = 0, j = 0;
        while (pre1 != null && post1 != null && j < b) {
    
    
            if (i != a - 1) {
    
    
                pre1 = pre1.next;
                i++;
            }
            if (j != b) {
    
    
                post1 = post1.next;
                j++;
            }
        }
        post1 = post1.next;
        while (post2.next != null) {
    
    
            post2 = post2.next;
        }
        pre1.next = list2;
        post2.next = post1;
        return list1;
    }
    

Guess you like

Origin blog.csdn.net/qq_43305829/article/details/132196563