双向链表的基本运算

#include<stdio.h>
#include<stdlib.h>

typedef struct dlnode
{
char data;
struct dlnode *prior,*next;
}DLNode;

DLNode *creat_dlinklist()
{
	DLNode *head,*s;
	char x;
	head=(DLNode*)malloc(sizeof(DLNode));
	head->prior=head;
	head->next=head;
	printf("请输入节点数据:\n");
	scanf("%c",&x);
	while(x!='\n')
	{
		s=(DLNode*)malloc(sizeof(DLNode));
		s->data=x;
		s->prior=head;
		s->next=head->next;
		head->next->prior=s;
		head->next=s;
		scanf("%c",&x);
	}
	return head;
}

DLNode *get_dlinklist(DLNode *head,int i)
{
	DLNode *p=head;
	int j=0;
	while(p->next!=head&&j<i)
	{
		p=p->next;
		j++;
	}
	if(p->next!=head)
		return p;
	else 
		return NULL;
}

void insert_dlinklist(DLNode *head,int i,char x)
{
	DLNode *p,*s;

	p=get_dlinklist(head,i-1);
	if(p==NULL)
		printf("错误!\n");
	else
	{
		s=(DLNode*)malloc(sizeof(DLNode));
		s->data=x;
		s->prior=p;
		s->next=p->next;
		p->next->prior=s;
		p->next=s;
	}
}

void del_dlinklist(DLNode *head,int i)
{
	DLNode *p;
	p=get_dlinklist(head,i);
	if(p==NULL)
		printf("这个元素不存在!\n");
	else
	{
		p->prior->next=p->next;
		p->next->prior=p->prior;
		free(p);
	}
}

void print1(DLNode *h)
{
	DLNode *p;
	p=h->next; 
	while(p!=h)
	{
	printf("%c->",p->data);
	p=p->next;
	}
	printf("\n");
}

void print2(DLNode *h)
{
	DLNode *p;
	p=h->prior;
	while(p!=h)
	{
		printf("%c->",p->data);
		p=p->prior;
	}
	printf("\n");
}

void main()
{
	DLNode *h,*p;
	int i;
	char x;
	h=creat_dlinklist();
	printf("后向输出双向循环链表:\n");
	print1(h);
	printf("前向输出双向循环链表:\n");
	print2(h);
	printf("请输入要查找元素的序号:\n");
	scanf("%d",&i);
	p=get_dlinklist(h,i);
	if(p!=NULL)
		printf("该元素的值为:%c\n",p->data);
	else
		printf("找不到!");
	printf("请输入要插入元素的位置和值(逗号隔开):\n");
	scanf("%d,%c",&i,&x);
	insert_dlinklist(h,i,x);
	print1(h);
	printf("请输入要删除节点的位置:\n");
	scanf("%d",&i);
	del_dlinklist(h,i);
	print1(h);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值