您的位置:首页 > 其它

lintcode-easy-Insertion Sort List

2016-02-25 15:38 295 查看
Sort a linked list using insertion sort.

Example

Given
1->3->2->0->null
, return
0->1->2->3->null
.

思路也比较直接,insertion sort,要注意的就是操作linkedlist的一些问题

/**
* 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) {
// write your code here

if(head == null || head.next == null)
return head;

ListNode fakehead = new ListNode(0);
fakehead.next = head;

ListNode prev = head;
ListNode curr = head.next;

while(curr != null){
if(curr.val > prev.val){
prev = curr;
curr = curr.next;
}
else{
ListNode p = fakehead;
while(p != prev && p.next.val < curr.val)
p = p.next;
prev.next = curr.next;
curr.next = p.next;
p.next = curr;
curr = prev.next;
}
}

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