AcWing 1451. 单链表快速排序
原题链接
简单
作者:
henhen敲
,
2020-05-15 00:12:01
,
所有人可见
,
阅读 1064
分别用pnode bnode 存储小于和大于head链表 留下head 将排好序的链表与head拼接起来
class Solution {
public ListNode quickSortList(ListNode head) {
if(head==null||head.next==null) return head;
ListNode bnode, pnode;
bnode = null;
pnode = null;
while(head.next!=null){
ListNode node = head.next;
head.next = node.next;
if(node.val<head.val){
if(pnode==null){
pnode = node;
pnode.next = null;
} else{
node.next = pnode;
pnode = node;
}
}
if(node.val>=head.val){
if(bnode==null){
bnode = node;
bnode.next = null;
}else{
node.next = bnode;
bnode = node;
}
}
}
ListNode n1 = quickSortList(pnode);
ListNode n2 = quickSortList(bnode);
head.next = n2;
if(n1!=null)getTail(n1).next = head;
else return head;
return n1;
}
public ListNode getTail(ListNode node){
if(node==null||node.next==null) return node;
return getTail(node.next);
}
}