使用VS2019编写双向单链表的完整代码

双向单链表完整代码,使用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;
}

注意我写的是单链表不是循环链表!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值