您的位置:首页 > 其它

Leetcode Insertion Sort List

2016-07-19 05:02 471 查看
Sort a linked list using insertion sort.

Difficulty: Medium

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
if(head == null) return null;
ListNode tail = head;
ListNode curr;
while(tail.next != null){
if(tail.next.val <= head.val){
ListNode temp = tail.next;
tail.next = temp.next;
temp.next = head;
head = temp;
}
else if(tail.next.val >= tail.val){
tail = tail.next;
}
else{
ListNode pre = null;
curr = head;
while(curr.val < tail.next.val){
pre = curr;
curr = curr.next;
}
ListNode temp = tail.next;
tail.next = temp.next;
pre.next = temp;
temp.next = curr;
}
}
return head;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: