您的位置:首页 > 其它

Leetcode---Insertion Sort List

2018-03-17 10:23 399 查看
Sort a linked list using insertion sort./**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head){
if(head == null || head.next == null) return head;
ListNode newhead = new ListNode(0);
newhead.next = head;
ListNode p, q, r;
p = head;
while((p != null)&&(p.next != null)){
if(p.val <= p.next.val)
p = p.next;
else{
q = p.next;
p.next = q.next;
r = newhead;
while(r.next.val <= q.val){
r = r.next;
}
q.next = r.next;
r.next = q;
}
}
return newhead.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Leetcode