#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct stu
{
//数据域
int num;
char name[32];
int age;
//指针域
struct stu *next;
struct stu *pre;
}STU;
extern STU* link_insert(STU *head,STU tmp);
extern void link_print(STU *head);
extern void link_search(STU *head);
extern STU* link_sort(STU *head);
int main(int argc,char *argv[])
{
char cmd[32];
STU *head=NULL;
STU tmp;
while(1)
{
//来个指令
printf("请输入指令:");
scanf("%s",cmd);
//指令的情况分一分
if(strcmp(cmd,"insert")==0)
{
//头部插入
//插入数据
printf("请输入要插入的数据:\n");
scanf("%d%s%d",&tmp.num,tmp.name,&tmp.age);
head=link_insert(head,tmp);
}
else if(strcmp(cmd,"print")==0)
{
//双向遍历
link_print(head);
}
else if(strcmp(cmd,"search")==0)
{
//找一找
link_search(head);
}
else if(strcmp(cmd,"sort")==0)
{
//排个序吧
head=link_sort(head);
}
else if(strcmp(cmd,"quit")==0)
break;
}
return 0;
}
//一个简单的头部插入函数
STU* link_insert(STU *head,STU tmp)
{
STU *pi=NULL;
//1、为数据申请一个堆区空间吧
pi=(STU *)calloc(1,sizeof(STU));
//2、将tmp的数据赋给pi
*pi=tmp;
//3、链表不存在时
if(NULL==head)
{
head=pi;
head->next=head;
head->pre=head;
}
//4、链表存在(挺复杂的)
else
{
pi->next=head;
pi->pre=head->pre;
pi->pre->next=pi;
head->pre=pi;
head=pi;
}
return head;
}
//一个复杂的双向遍历函数
void link_print(STU *head)
{
if(NULL==head)//这该死的链表还没写呢
{
printf("link not found!!!");
return ;
}
else//链表找到了
{
STU *pb=head;//头
STU *pf=head->pre;//尾
printf("双向遍历的结果哦!\n");
do
{
if(pb==pf)//头尾合一
{
printf("%d %s %d \n",pb->num,pb->name,pb->age);//打印一个
break;
}
printf("%d %s %d \n",pb->num,pb->name,pb->age);
printf("%d %s %d \n",pf->num,pf->name,pf->age);
pb=pb->next;//移动
pf=pf->pre;//我也来
}
while(pb->pre != pf);
}
return;
}
//简单的查找函数
void link_search(STU *head)
{
//链表不存在的情况
if(NULL==head)
{
printf("link not found!!!\n");
return;
}
else//链表存在
{
STU *pi=head;
STU *pb=head->pre;
char name[32];
printf("请输入要查找的节点名字:");
scanf("%s",name);
//查找
do
{
if(strcmp(name,pi->name) == 0 )//pi找到了name
{
printf("%d %s %d \n",pi->num,pi->name,pi->age);
break;
}
else if(strcmp(name,pb->name) == 0)//pb找到了name
{
printf("%d %s %d \n",pb->num,pb->name,pb->age);
break;
}
pi=pi->next;//我往后移
pb=pb->pre;//我往前移动
}
while(pb !=pi && pi->pre != pb);//不相遇,不相等
}
return;
}
//排序函数
STU* link_sort(STU *head)
{
//链表不存在的情况
if(NULL==head)
{
printf("link not found!!!\n");
return head;
}
else//链表存在,用选择排序法来搞
{
STU *p_i=head;
STU *pb=head;
while(p_i->next!=pb)//外层循环
{
STU *p_min=p_i;
STU *p_j=p_min->next;
while(p_j != pb)//内层循环
{
if(p_min->num > p_j->num)
p_min = p_j;//最小值
p_j = p_j->next;//右移
}
if(p_min != p_i)//排序
{
//整体交换
STU tmp;
tmp = *p_i;
*p_i = *p_min;
*p_min = tmp;
//指针域交换回来
tmp.next = p_i->next;
tmp.pre = p_i->pre;
p_i->next = p_min->next;
p_i->pre = p_min->pre;
p_min->next = tmp.next;
p_min->pre = tmp.pre;
}
p_i = p_i->next;//外层右移
}
}
return head;
}
运行结果: