直接插入排序,链式
#include <iostream>
using namespace std;
/*
*writer:yaojinhui
*/
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;
}