#include < iostream >
#include < cstdlib >
using namespace std;
// 结点的定义
typedef struct DLNode{
int data;
struct DLNode* prior;
struct DLNode* next;
}DLNode;
// 创建链表 (尾插法)
void createLinklist(DLNode *&S,int a[],int n) // a??
{
DLNode *s,*r; // s指向尾结点,r指向头结点,两个都要加 *
DLNode *p; // 用于删除创建后不必要的头结点
S = (DLNode *)malloc(sizeof(DLNode)); // 创建头结点
S->prior = S; // prior和next 指针均指向头结点
S->next = S;
r = S; // r始终指向终端结点
for(int i=0;i<n;i++)
{
s = (DLNode *)malloc(sizeof(DLNode));
s->data = a[i]; // 给 s 赋值 ??
s->next = r->next; // 改变指针方向,双向
r->next = s;
s->next->prior = s;
s->prior = r;
r = s;
}
}
// 插入排序
void insertsort(DLNode *&S)
{
DLNode *p,*m;
int temp; // 用于保存要插入的值
p = S->next->next;
while(p!=S){
m = p->prior; // m指向p前面一个元素,依次比较
if((m->data)>(p->data))
{
while(m!=S && (m->data)>(p->data)){
m = m->prior;
}
// q指向p
DLNode* q;
q = p;
// 暂时将p移除链表
p->prior->next = p->next;
p->next->prior = p->prior;
// 插入
q->next = m->next;
q->prior = m;
m->next = q;
q->next->prior = q;
}
p=p->next;
}
}
// 显示
void display(DLNode *S)
{
DLNode* p;
p = S->next;
while(p != S){
cout<<p->data;
p = p->next;
}
}
// 销毁链表
void destroy(DLNode *&S)
{
DLNode* p;
p = S;
while(p->next != S){
DLNode* tmp = p;
p = p->next;
free(tmp);
}
free(p);
}
int main()
{
int a[] = {3,6,5,9,8,0};
DLNode* L;
createLinklist(L,a,6);
insertsort(L);
display(L);
return 0;
}