148. 排序链表
链接:https://leetcode-cn.com/problems/sort-list/solution/148-pai-xu-lian-biao-by-oyzg-sta1/
解题思路
解法一:
用一个容器来装入每个节点,然后再排序,我这里使用的是ArrayList
解法二:
插入排序
代码:
解法一:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
ArrayList<ListNode> list = new ArrayList<ListNode>();
ListNode cur = head;
while(cur != null) {
list.add(cur);
ListNode ln = cur;
cur = cur.next;
ln.next = null;
}
list.sort(new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
// TODO Auto-generated method stub
return o1.val - o2.val;
}
});
ListNode node = new ListNode(0);
cur = node;
for(ListNode l : list) {
cur.next = l;
cur = cur.next;
}
return node.next;
}
}
public ListNode sortList(ListNode head) {
if(head == null) return null;
return sortList(head, head);
}
public ListNode sortList(ListNode head, ListNode tail) {
if(tail.next == null) return head;
ListNode node = tail.next;
if(node.val >= tail.val) return sortList(head, node);
tail.next = tail.next.next;
if(node.val <= head.val) {
node.next = head;
return sortList(node, tail);
}
ListNode cur = head;
while(cur != null) {
if(cur.next.val >= node.val) {
node.next = cur.next;
cur.next = node;
break;
}
cur = cur.next;
}
return sortList(head, tail);
}