Insertion Sort List Total Accepted: 18506 Total Submissions: 73505 My Submissions
Sort a linked list using insertion sort.
链表的插入排序,没什么难度,注意边界条件
/**
*
* 插入排序链表
* @author zhouyf
*
*/
public class InsertionSortList {
static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public ListNode insertionSortList(ListNode head) {
if (head == null) {
return null;
}
if (head.next == null) {
return head;
}
ListNode newHead = head;
ListNode curNode = head.next;
ListNode curPreNode = head;
while (curNode != null) {
ListNode pNode = newHead;
ListNode preNode = null;
while (pNode != curNode) {
if (curNode.val < pNode.val) {
if (preNode == null) {
ListNode oldHead = newHead;
newHead = curNode;
curPreNode.next = curNode.next;
curNode.next = oldHead;
} else {
ListNode old = curNode.next;
curNode.next = preNode.next;
preNode.next = curNode;
curPreNode.next = old;
}
curNode = curPreNode.next;
break;
} else {
preNode = pNode;
pNode = pNode.next;
}
}
if (pNode == curNode) {
curPreNode = curNode;
curNode = curNode.next;
}
}
return newHead;
}
}