[Linked List] Sorting of a singly linked list (merge sort)

[Linked list] Merge k sorted linked lists (merge sort) - Programmer Sought

 It is equivalent to merging n ordered singly linked lists, and each singly linked list has a length of 1.

Add each singly linked list to the list, and then apply the merge sort function.

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    public ListNode sortInList (ListNode head) {
        // write code here
        if(head==null)return null;
        ArrayList<ListNode>list=new ArrayList<>();
        ListNode p=head;
        while(p!=null){
            ListNode q=p.next;
            p.next=null;
            list.add(p);
            p=q;
        }
        return mergeKLists(list);
        
    }
       public ListNode merge(ListNode l1,ListNode l2){
        if(l1==null||l2==null){
            return l1==null?l2:l1;
        }
        ListNode dummyNode=new ListNode(-1);
        ListNode cur=dummyNode;
        while(l1!=null&&l2!=null){
            if(l1.val<l2.val){
                cur.next=l1;
                l1=l1.next;
            }else{
                cur.next=l2;
                l2=l2.next;
            }
            cur=cur.next;
        }
        cur.next=(l1==null?l2:l1);
        return dummyNode.next;
    }
      public ListNode mergeList(ArrayList<ListNode> lists,int L,int R){
        if(L==R){
            return lists.get(L);
        }
        if(L>R)return null;
        int mid=L+((R-L)>>1);
        return merge(mergeList(lists,L,mid),mergeList(lists,mid+1,R));
    }
     public ListNode mergeKLists(ArrayList<ListNode> lists) {
        return mergeList(lists,0,lists.size()-1);
    }
}

Guess you like

Origin blog.csdn.net/m0_52043808/article/details/124425014