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

leetcode_147_Insertion Sort Lis

时间:2015-02-15 12:12:01      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:linked_list   c++   leetcode   

欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢技术分享


Insertion Sort List


Sort a linked list using insertion sort.


class Solution {
public:
    ListNode *insertionSortList(ListNode *head) {
		if( head==NULL || head->next==NULL )
			return head;
		ListNode *p = new ListNode(-1);
		p->next = head;
		ListNode *pre = head;
		ListNode *cur = head->next;
		while(cur)
		{
			if(cur->val>=pre->val)
			{
				pre = cur;
				cur = cur->next;
			}
			else
			{
			//first find the insert position 
				ListNode *inserpre = p;
				ListNode *insercur = p->next;
				while( insercur->val < cur->val )
				{
					inserpre = insercur;
					insercur = insercur->next;
				}
				pre->next = cur->next;
				cur->next = insercur;
				inserpre->next = cur;
				cur = pre->next;
			}
		}
		head = p->next;
		return head;
    }
};


#include<iostream>
#include<stack>

using namespace std;

#define N 5

struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode *insertionSortList(ListNode *head) {
		if( head==NULL || head->next==NULL )
			return head;
		ListNode *p = new ListNode(-1);
		p->next = head;
		ListNode *pre = head;
		ListNode *cur = head->next;
		while(cur)
		{
			if(cur->val>=pre->val)
			{
				pre = cur;
				cur = cur->next;
			}
			else
			{
				ListNode *inserpre = p;
				ListNode *insercur = p->next;
				while( insercur->val < cur->val )
				{
					inserpre = insercur;
					insercur = insercur->next;
				}
				pre->next = cur->next;
				cur->next = insercur;
				inserpre->next = cur;
				cur = pre->next;
			}
		}
		head = p->next;
		return head;
    }
};

ListNode *creatlist()
{
	ListNode *head = NULL;
	ListNode *p;
	for(int i=0; i<N; i++)
	{
		int a;
		cin>>a;
		p = (ListNode*) malloc(sizeof(ListNode));
		p->val = a;
		p->next = head;
		head = p;
	}
	return head;
}

int main()
{
	ListNode *list = creatlist();
	Solution lin;
	ListNode *outlist = lin.insertionSortList ( list );
	for(int i=0; i<N; i++)
	{
		cout<<outlist->val;
		outlist = outlist->next;
	}
}


leetcode_147_Insertion Sort Lis

标签:linked_list   c++   leetcode   

原文地址:http://blog.csdn.net/keyyuanxin/article/details/43833917

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