双向链表,又可以称为双向循环链表。
双向链表中插入删除操作的详细解析可以看这篇文章:双链表,下面是个人写的简单代码,仅供参考。
#include
#include
struct DulNode
{
int data;
DulNode *prior;
DulNode *next;
};
//初始化空的头结点
DulNode *InitDulNode()
{
DulNode *head;
head = (DulNode*)malloc(sizeof(DulNode));
head->next = head;
head->prior = head;
return head;
}
//初始化数据
void InitdulList(DulNode *dulList)
{
DulNode *node;
node = (DulNode*)malloc(sizeof(DulNode));
printf("输入数据:");
scanf("%d",&node->data);
//新节点的next指针域
node->next = dulList->next;
dulList->next->prior = node;
node->prior = dulList;
dulList->next = node;
}
void Insert(DulNode *dulList)
{
DulNode *node;
node = (DulNode*)malloc(sizeof(DulNode));
printf("输入插入数据:");
scanf("%d",&node->data);
printf("输入插入位置:");
int position;
scanf("%d",&position);
int i=0;
dulList = dulList->next;
while(i < position-1 && dulList != NULL)
{
i++;
dulList = dulList->next;
}
node->next = dulList->next;
dulList->next->prior = node;
dulList->next = node;
node->prior = dulList;
}
void Delete(DulNode *dulList)
{
printf("输入删除位置:");
int position;
scanf("%d",&position);
int i=0;
//dulList = dulList->next;
while(i < position-1 && dulList->next != NULL)
{
i++;
dulList = dulList->next;
}
DulNode *dul = dulList->next;
dulList->next = dul->next;
dul->next->prior = dulList;
printf("删除的数据为:%d\n",dul->data);
free(dul);
}
void Output(DulNode *dulList)
{
DulNode *temp = dulList;//temp指向尾节点
while(dulList->prior != temp)
{
printf("数据为:%d\n",dulList->prior->data);
//printf("数据为:%d\n",dulList->next->next->next->data);
dulList = dulList->prior;
}
}
void menu()
{
printf("****************\n");
printf(" * 1--初始化\n");
printf(" * 2--添加数据\n");
printf(" * 3--删除数据\n");
printf(" * 4--查看数据\n");
printf(" * 0--退出\n");
printf("****************\n");
}
int main()
{
DulNode *dulList,*p;
p = dulList = InitDulNode();
int i = 0;
int choose;
do
{
menu();
printf("输入您的选择:");
scanf("%d",&choose);
getchar();
switch(choose)
{
case 1:
//相当于每次都在第一个位置插入
while(i<3)
{
InitdulList(p);
//p = p->next;//相当于每次都在最后一个位置插入
i++;
}
break;
case 2:
Insert(dulList);
break;
case 3:
Delete(dulList);
break;
case 4:
Output(dulList);
break;
case 0:
break;
}
}while(choose != 0);
return 0;
}