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

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)