码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 链表 Insertion Sort List

时间:2014-10-13 14:11:30      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:style   http   color   io   os   ar   sp   div   on   

Insertion Sort List

 Total Accepted: 24444 Total Submissions: 96639My Submissions

Sort a linked list using insertion sort.




题意:用插入排序对一个链表排序
思路:
插入排序对当前元素在前面已经排好的元素中找到一个位置把它插入
可以设置一个指向头节点的dummy元素,统一操作
注:链表中的交换节点操作,不能简单地只交换节点里的value,因为value有可能是很复杂的类,那样要调用拷贝构造函数、赋值函数,比较费时间。
复杂度:时间O(n^2),空间O(1)

ListNode *insertionSortList(ListNode *head) {
	if(!head) return NULL;
	ListNode dummy(-1);
	dummy.next = head;
	ListNode *cur = head->next;
	head->next = NULL;
	while(cur){
		ListNode *cur_next = cur->next;
		ListNode *pos = &dummy;
		while(pos->next != NULL && pos->next->val <= cur->val){
			pos = pos->next;
		}		
		ListNode *tem = pos->next;
		pos->next = cur;
		cur->next = tem;
		cur = cur_next;
	}
	return dummy.next;
}


leetcode 链表 Insertion Sort List

标签:style   http   color   io   os   ar   sp   div   on   

原文地址:http://blog.csdn.net/zhengsenlie/article/details/40042619

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!