[LeetCode] Insertion Sort List
2014-08-18 15:25
357 查看
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;
}
}
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;
}
}
相关文章推荐
- LeetCode 147 Insertion Sort List(链表插入排序)
- LeetCode: Insertion Sort List(外加对单链表类题目的思考总结)
- leetcode147~Insertion Sort List
- Leetcode:Insertion Sort List
- C实现 LeetCode->Insertion Sort List(排序)(单链表)
- Insertion Sort List (LeetCode)
- 【Leetcode】Insertion Sort List
- [LeetCode]Insertion Sort List
- [LeetCode] Insertion Sort List
- leetcode Insertion Sort List(*)
- [LeetCode] Insertion Sort List
- LeetCode--insertion-sort-list
- 【leetcode】【单链表】【147】Insertion Sort List
- 59_leetcode_Insertion Sort List
- LeetCode——Insertion Sort List
- LeetCode_Insertion Sort List
- Insertion Sort List Leetcode Python
- leetcode_Sort a linked list using insertion sort.
- leetcode Insertion Sort List
- (Leetcode 147)Insertion Sort List