题目
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
示例 1:
输入:head = [4,2,1,3]
输出:[1,2,3,4]
分析
这道题目的思路也比较明确,我们可以用递归排序的思路,先不断拆分链表直到只剩下一个结点,然后再合并俩个有序列表。拆分链表可以用快慢指针的方法
java
public class LinkNode {
int val;
LinkNode next;
public LinkNode(int data) {
this.val = data;
this.next = null;
}
}
public class LinkList {
LinkNode head;
public LinkList() {
this.head = null;
}
public LinkNode getHead() {
return this.head;
}
//添加元素
public void addNode(int data) {
LinkNode node = new LinkNode(data);
if (this.head == null) {
this.head = node;
} else {
LinkNode cur = this.head;
while(cur.next != null) {
cur = cur.next;
}
cur.next = node;
}
}
//正序打印
public void print(LinkNode node) {
while(node != null) {
System.out.print(node.val);
System.out.print(" ");
node = node.next;
}
System.out.println();
}
public LinkNode sort(LinkNode head) {
if(head == null || head.next == null) {
return head;
}
LinkNode fast = head;
LinkNode slow = head;
LinkNode pre = null;
while(fast != null && fast.next != null) {
pre = slow;
slow = slow.next;
fast = fast.next.next;
}
pre.next = null;
return merge(sort(slow),sort(head));
}
public LinkNode merge(LinkNode slow,LinkNode fast) {
LinkNode dummy = new LinkNode(0);
LinkNode p = dummy;
while(slow != null && fast != null) {
if(slow.val < fast.val) {
p.next = slow;
p = p.next;
slow = slow.next;
} else {
p.next = fast;
p = p.next;
fast = fast.next;
}
}
while(slow != null) {
p.next = slow;
p = p.next;
slow = slow.next;
}
while(fast != null) {
p.next = fast;
p = p.next;
fast = fast.next;
}
return dummy.next;
}
}
public class sortList {
public static void main(String[] args) {
LinkList list = new LinkList();
list.addNode(-1);
list.addNode(5);
list.addNode(3);
list.addNode(4);
list.addNode(0);
LinkNode head = list.sort(list.getHead());
list.print(head);
}
}