您的位置:首页 > 其它

LintCode 链表插入排序

2015-06-25 15:19 363 查看
用插入排序对链表排序

样例

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