Leetcode Insertion Sort List
2014-05-08 13:30
351 查看
Sort a linked list using insertion sort.
链表的插入排序,其实有2种特殊情况:
1、插入的值插入到已排序的末尾。
2、插入的值插入到已排序的最前端。
主要设置了3个指针。
1、pStart是已排序链表的开始位置。
2、pInsert是待插入的位置。
3、pEnd是下一个等待排序的位置。
key:每个已排序的链表最后的Node的next指针为null。这样可以防止循环链表,已得不到正确值。
链表的插入排序,其实有2种特殊情况:
1、插入的值插入到已排序的末尾。
2、插入的值插入到已排序的最前端。
主要设置了3个指针。
1、pStart是已排序链表的开始位置。
2、pInsert是待插入的位置。
3、pEnd是下一个等待排序的位置。
key:每个已排序的链表最后的Node的next指针为null。这样可以防止循环链表,已得不到正确值。
public class Solution {
public ListNode insertionSortList(ListNode head) {
if(head == null||head.next == null)return head;
ListNode pStart = head;
ListNode pInsert = head.next;
pStart.next = null;
ListNode pEnd = head;
while(pInsert != null)
{
pEnd = pInsert.next;
pStart = sort(pStart,pInsert);
pInsert = pEnd;
}
head = pStart;
return head;
}
public ListNode sort(ListNode head,ListNode insert)
{
ListNode start = head;
ListNode pStr = head;
if(head == null)return head;
while(start.val < insert.val && start.next != null)
{
pStr = start;
start = start.next;
}
if(start.val >= insert.val && start == head)
{
insert.next = head;
head = insert;
}
else if(start.val >= insert.val)
{
pStr.next = insert;
insert.next = start;
}
else if(start.next == null)
{
start.next = insert;
insert.next = null;
}
return head;
}
}
public ListNode insertionSortList(ListNode head) {
if(head == null||head.next == null)return head;
ListNode pStart = head;
ListNode pInsert = head.next;
pStart.next = null;
ListNode pEnd = head;
while(pInsert != null)
{
pEnd = pInsert.next;
pStart = sort(pStart,pInsert);
pInsert = pEnd;
}
head = pStart;
return head;
}
public ListNode sort(ListNode head,ListNode insert)
{
ListNode start = head;
ListNode pStr = head;
if(head == null)return head;
while(start.val < insert.val && start.next != null)
{
pStr = start;
start = start.next;
}
if(start.val >= insert.val && start == head)
{
insert.next = head;
head = insert;
}
else if(start.val >= insert.val)
{
pStr.next = insert;
insert.next = start;
}
else if(start.next == null)
{
start.next = insert;
insert.next = null;
}
return head;
}
}
相关文章推荐
- Leetcode[147]-Insertion Sort List
- 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】Insertion Sort List
- leetcode 【 Insertion Sort List 】 python 实现
- Leetcode: Insertion Sort List
- LeetCode - Insertion Sort List
- [leetcode] Insertion Sort List
- leetcode之Insertion Sort List
- Leetcode 147 Insertion Sort List
- 【LeetCode】Insertion Sort List
- Leetcode: Insertion Sort List
- LeetCode: Insertion Sort List
- leetcode题目解答---Insertion Sort List
- leetcode -- Insertion Sort List -- 重点,需要优化
- leetcode之Insertion Sort List