您的位置:首页 > 其它

[LeetCode]147 Insertion Sort List

2015-01-08 18:29 405 查看
https://oj.leetcode.com/problems/insertion-sort-list/
http://blog.csdn.net/linhuanmars/article/details/21144553
/**
* 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;

// Add dummy head
ListNode dummyhead = new ListNode(0);

ListNode pre;
ListNode cur = head;

while(cur!=null)
{
ListNode next = cur.next;
pre = dummyhead;
while(pre.next!=null && pre.next.val<=cur.val)
pre = pre.next;

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