首页 > 其他 > 详细

[LeetCode 147] Insertion Sort List

时间:2015-03-26 09:14:40      阅读:209      评论:0      收藏:0      [点我收藏+]

题目链接:insertion-sort-list


/**
 * 
	Sort a linked list using insertion sort.
 *
 */
public class InsertionSortList {

	public class ListNode {
		int val;
		ListNode next;

		ListNode(int x) {
			val = x;
			next = null;
		}
	}
	
//	21 / 21 test cases passed.
//	Status: Accepted
//	Runtime: 312 ms
//	Submitted: 0 minutes ago

	//时间复杂度O(n * n) 空间复杂度 O(1)
	public ListNode insertionSortList(ListNode head) {
		ListNode preHead = new ListNode(-1);
		while(head != null) {
			ListNode cur = preHead;
			int val = head.val;
			while(cur.next != null) {
				if(cur.next.val >= val) {
					break;
				}
				cur = cur.next;
			}
			ListNode curNext = cur.next;
			cur.next = head;
			head = head.next;
			cur.next.next = curNext;
		}
		return preHead.next;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}


[LeetCode 147] Insertion Sort List

原文:http://blog.csdn.net/ever223/article/details/44628555

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!