LintCode 链表插入排序

来源:互联网 发布:视频日语同声翻译软件 编辑:程序博客网 时间:2024/04/30 20:03

用插入排序对链表排序
样例
Given 1->3->2->0->null, return 0->1->2->3->null

Sort a linked list using insertion sort.
Example
Given 1->3->2->0->null, return 0->1->2->3->null.

/** * Definition for ListNode. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int val) { *         this.val = val; *         this.next = null; *     } * } */ public class Solution {    /**     * @param head: The first node of linked list.     * @return: The head of linked list.     */    public ListNode insertionSortList(ListNode head) {        if(null == head|| null == head.next) return head;        ListNode newhead = head;        head = head.next;        newhead.next = null;        ListNode q = newhead, p = head;        while(null != p) {            ListNode r = p.next;            if(q.val >= p.val) {//插在头部                p.next = q;                newhead = p;                q = p;                p = r;                continue;            }            while(null != q.next) {//插在中间                if(q.val < p.val && q.next.val >= p.val) {                    p.next = q.next;                    q.next = p;                }                q = q.next;            }            if(q.val < p.val) {//插在尾部                q.next = p;                p.next = null;            }            p = r;            q = newhead;        }        return newhead;    }}
0 0
原创粉丝点击