设为首页 加入收藏

TOP

[LeetCode 147]Insertion Sort List
2015-11-21 01:05:15 来源: 作者: 【 】 浏览:3
Tags:LeetCode 147 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| Triangle 三角矩阵的最.. 下一篇LeetCode| Decode ways

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: