您的位置:首页 > 其它

Leetcode: Insertion Sort List

2013-11-14 04:58 393 查看
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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (head == null)
return head;
ListNode res = new ListNode(Integer.MIN_VALUE);
ListNode pre = res;
ListNode cur = null;
ListNode next;
while (head != null) {
next = head;
head = head.next;
next.next = null;
pre = res;
cur = pre.next;
while (cur != null && cur.val < next.val) {
cur = cur.next;
pre = pre.next;
}
pre.next = next;
next.next = cur;
}
return res.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: