Topic link: LeeCode148 sorted linked list
Topic description:
Look at the topic to know that it is to merge and sort, and then review the knowledge of merge and sort, using a linked list to achieve merging is still a bit convoluted, or to look at the solution of the problem to make it, but the idea of merging with an array is Same, I won’t elaborate
class Solution {
//递归函数,用来将链表不断的分成两个再有序合并
public static ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode mid=getMid(head);
ListNode r=mid.next;
mid.next=null;
return merge(sortList(head),sortList(r));
}
//合并函数,将两个链表有序合并到一起
public static ListNode merge(ListNode l,ListNode r){
ListNode head=new ListNode();
ListNode le=l,ri=r;
//先单独走一遍确定合成串的头节点
if (le.val > ri.val) {
head=ri;
ri=ri.next;
}else{
head=le;
le=le.next;
}
ListNode node=head;
//不断地将小的数往上拼
while (le != null && ri != null) {
if (le.val > ri.val) {
node.next=ri;
node=node.next;
ri=ri.next;
}else {
node.next=le;
node=node.next;
le=le.next;
}
}
//如果循环结束有一个链表有剩余则按顺序拼上即可
while (le!=null){
node.next=le;
node=node.next;
le=le.next;
}
while (ri!=null){
node.next=ri;
ri=ri.next;
node=node.next;
}
return head;
}
//取中间节点的函数,快慢指针,慢指针一次走一步,快指针一次走两步,快指针到达终点的时候慢指针到中间
public static ListNode getMid(ListNode head){
if(head==null||head.next==null)return head;
ListNode slow=head;
ListNode fast=head;
while(fast.next!=null&&fast.next.next!=null){
slow=slow.next;
fast=fast.next.next;
}
return slow;
}
}