双向单链表完整代码,使用VS2019版本:`
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct dunode
{
int data;
struct dunode* prior;
struct dunode* next;
} DuLinkList;
DuLinkList* MakeEmpty()
{
DuLinkList* PtrL;
PtrL = (DuLinkList*)malloc(sizeof(DuLinkList));
PtrL->prior = PtrL->next = PtrL;
return PtrL;
}
void CreatLink(DuLinkList*L)
{
int num,data;
DuLinkList*p,*s;
p = L;
printf("请输入建立双向链表的元素个数:");
scanf_s("%d", &num);
for (int i = 1; i <= num; i++)
{
s = (DuLinkList*)malloc(sizeof(DuLinkList));
printf("请输入第%d个数:", i);
scanf_s("%d", &s->data);
s->prior = p->prior;
p->prior->next = s;
s->next = NULL;
p->prior = s;
}
}
void InsetLink(DuLinkList* L)
{
int data;
DuLinkList* s,*p;
p = L;
printf("请输入插入的元素:");
scanf_s("%d", &data);
s = (DuLinkList*)malloc(sizeof(DuLinkList));
s->data = data;
s->prior = p->prior;
p->prior->next = s;
p->prior = s;
s->next = NULL;
}
void DeleteLink(DuLinkList* L)
{
int data;
DuLinkList* s, * p;
p = L->next;
printf("请输入删除的数据:");
scanf_s("%d", &data);
while (p != NULL && p->data != data)
p = p->next;
if (p != NULL)
{
if (p->next != NULL)
{
p->next->prior = p->prior;
p->prior->next = p->next;
free(p);
printf("%d已删除!\n", data);
}
else {
p->prior->next = NULL;
free(p);
printf("%d已删除!\n", data);
}
}
else printf("%d不存在!\n",data);
}
void DisplayLink1(DuLinkList* L)
{
DuLinkList* p, * s;
p = L->next;
while (p != NULL)
{
printf("%5d", p->data);
p = p->next;
}
printf("\n");
}
void DisplayLink2(DuLinkList* L)
{
DuLinkList* p= L->prior;
while (p!= L)
{
printf("%5d", p->data);
p = p->prior;
}
printf("\n");
}
void Menu()
{
printf("\n-----------操作指南-----------\n\n");
printf(" 1.建立双向单链表\n");
printf(" 2.插入数据元素\n");
printf(" 3.删除数据元素\n");
printf(" 4.正向顺序输出\n");
printf(" 5.逆向顺序输出\n");
printf(" 0.退出\n");
printf("\n------------------------------\n\n");
}
int main()
{
DuLinkList* PtrL= MakeEmpty();
int choice;
while (1) {
Menu();
printf("请输入您的选择:");
scanf_s("%d", &choice);
switch (choice) {
case 1:CreatLink(PtrL); break;
case 2:InsetLink(PtrL); break;
case 3:DeleteLink(PtrL); break;
case 4:DisplayLink1(PtrL); break;
case 5:DisplayLink2(PtrL); break;
case 0:exit(0);
default:break;
}
}
system("pause");
return 0;
}
注意我写的是单链表不是循环链表!