您的位置:首页 > 其它

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。这样可以防止循环链表,已得不到正确值。

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;
    }
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: