`
hcx2013
  • 浏览: 83020 次
社区版块
存档分类
最新评论

Insertion Sort List

 
阅读更多

Sort a linked list using insertion sort.

 

/**
 * 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 || head.next == null) {
        	return head;
        }
        ListNode res = new ListNode(0);
        ListNode cur = head;
        while (cur != null) {
        	ListNode pre = res;
        	ListNode next = cur.next;
        	while (pre.next != null && pre.next.val < cur.val) {
        		pre = pre.next;
        	}
        	cur.next = pre.next;
        	pre.next = cur;
        	cur = next;
        }
        return res.next;
    }
}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics