1. 程式人生 > >C++ 連結串列直接插入排序

C++ 連結串列直接插入排序

#include<bits/stdc++.h>


/*
* Created by HarvestWu on 2018/07/24.
*/
using namespace std;

typedef int ElemType;
typedef int Status;

typedef struct LNode
{
	ElemType data;
	struct LNode *next;
}LNode, *LinkList;


//尾插法建立連結串列
void CreateList_L(LinkList &L, ElemType R[],int n)
{
	
	L = (LinkList)malloc(sizeof(LNode));
	L->next = NULL;			
	LinkList p,t;
	t = L;
	for (int i = 0; i < n; i++)
	{
		p = (LinkList)malloc(sizeof(LNode));	
		p->data = R[i];
		t->next = p;
		t = p;
	}
	t->next = NULL;
}

//連結串列直接插入排序
void Sort(LinkList &L)
{
	LinkList p, p1, q, pre;
	if (L->next != NULL)
	{
		p = L->next->next;
		L->next->next = NULL;
		while (p != NULL)
		{
			pre = L;  //pre指向q的前驅
			q = pre->next;
			while (q != NULL&&q->data < p->data)//從連結串列第二個結點開始找比當前插入值大的結點
			{
				pre = q;
				q = q->next;
			}
			p1 = p->next;//將p插入到結點pre和p之間
			p->next = pre->next;
			pre->next = p;
			p = p1;
		}
	}
}

//連結串列遍歷
void Display(LinkList &L)
{
	LinkList p;
	p = L->next;
	while (p)		
	{
		cout<<p->data<<" ";
		p = p->next;
	}
	cout << endl;
}
int main()
{
	LinkList L;
	ElemType R[] = { 1, 8, 6, 9, 7, 12, 0, 3, 8, 4, 5 };
	CreateList_L(L, R, 10);
	Sort(L);
	Display(L);
	return 0;
}