题解 | #单链表的排序#
单链表的排序
http://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
选择排序 从无序里面选最小的 放入有序
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) {
//边界条件
if (head == null || head.next == null) {
return head;
}
//哑节点
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode sorted = dummy;
//遍历
while (sorted.next != null) {
ListNode pre = sorted;
ListNode cur = sorted.next;
ListNode preMin = null;
ListNode min = null;
while (cur != null) {
if (min == null || cur.val < min.val) {
preMin = pre;
min = cur;
}
pre = pre.next;
cur = cur.next;
}
preMin.next = min.next;
min.next = sorted.next;
sorted.next = min;
sorted = min;
}
return dummy.next;
}
}