码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode_147题——Insertion Sort List(线性表,插入排序)

时间:2015-04-26 10:39:42      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

Insertion Sort List

 Total Accepted: 40386 Total Submissions: 154512My Submissions

 

Sort a linked list using insertion sort.

 

Hide Tags
 Linked List Sort
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

   这道题没啥好说的,主要是考察线性表的操作和插入排序

#include<iostream>

using namespace std;

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

ListNode* insertionSortList(ListNode* head)
{
	ListNode* ptr=head;
	ListNode* ptr_start;
	ListNode* ptr_end;
	ListNode* temp;
	ListNode* cur;
	ListNode* pre;
	ListNode* pre1;

	ptr_start=ptr_end=ptr;

	if(ptr==NULL)
		return ptr;
	if(ptr->next==NULL)
		return ptr;

	ptr_start=ptr;
	ptr_end=ptr->next;

	if(ptr_start->val>=ptr_end->val)
	{
		ptr_start->next=ptr_end->next;
		ptr_end->next=ptr_start;
		temp=ptr_start;
		ptr_start=ptr_end;
		ptr_end=temp;
		ptr=ptr_start;
	}
	cur=ptr_end->next;
	while(cur)
	{
		pre=ptr_start;
		pre1=ptr_start->next;

		if(cur->val<=pre->val)
		{
			ptr_end->next=cur->next;
			cur->next=ptr_start;
			ptr_start=cur;
			ptr=ptr_start;
			cur=ptr_end->next;
		}
		else
		{
			int flag=0;
			while(pre1!=cur)
			{
				if(cur->val<=pre1->val)
				{
					ptr_end->next=cur->next;
					cur->next=pre1;
					pre->next=cur;
					flag=1;
					cur=ptr_end->next;
					break;
				}
				else
				{
					pre1=pre1->next;
					pre=pre->next;
				}
			}
			if(flag==0)
			{
				ptr_end=ptr_end->next;
				cur=cur->next;
			}
		}

	}

	return ptr;


}
int main()
{
	ListNode* head;
	head=(ListNode*)malloc(sizeof(ListNode));
	head->val=2;

	ListNode* ptr2;
	ptr2=(ListNode*)malloc(sizeof(ListNode));
	head->next=ptr2;
	head->next->next=NULL;
	ptr2->val=1;

	ListNode* ptr3;
	ptr3=(ListNode*)malloc(sizeof(ListNode));
	head->next->next=ptr3;
	ptr3->val=4;

	ListNode* ptr4;
	ptr4=(ListNode*)malloc(sizeof(ListNode));
	head->next->next->next=ptr4;
	ptr4->val=3;
	ptr4->next=NULL;

	cout<<head->val<<‘ ‘<<head->next->val<<‘ ‘<<head->next->next->val<<‘ ‘<<head->next->next->next->val<<endl;

	ListNode* head1;
	head1=insertionSortList(head);
	cout<<head1->val<<‘ ‘<<head1->next->val<<‘ ‘<<head1->next->next->val<<‘ ‘<<head1->next->next->next->val<<endl;
}

  

leetcode_147题——Insertion Sort List(线性表,插入排序)

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4457338.html

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