4双向链表相关知识

#include<stdio.h>
#include<stdlib.h>
#define SIZE sizeof(struct linklist)
struct linklist{
	struct linklist *front;
	int data;
	struct linklist *back;
}*first=NULL;
int main(void)
{
	int n,i,j;
	struct linklist *p,*p1,*p2; 
	first=(struct linklist *)malloc(SIZE);//为头节空点申请内存空间 
	if(first==NULL)
	{
		printf("error\n");
		return -1;
	}
	else/////////////////////////////////建立头空节点成功 
	{
		first->back=NULL;
		first->front=NULL;
		printf("First node established successfully\n");
	}
	while(1)/////////////////////需要建立n个节点实现对数字n的输入 
	{
		if(1==scanf("%d",&n)){
			getchar();
			break;
		}
		else{
			getchar();
			printf("Input form error\n");
			return -1;
		}
	}/////////////////////////// 需要建立n个节点实现对数字n的输入 
	i=n;
	while(i)
	{
		p1=(struct linklist *)malloc(SIZE);
		if(p1==NULL)
		return -1;
		if(i==n)
		{
			scanf("%d",&p1->data);//不太安全(简略写法) 
			getchar();
			first->back=p1;
			p1->back=NULL;
			p1->front=first;
			p2=p1;// 记录p1否则在下次内存申请时节点地址 
			
		}
		else
		{
			scanf("%d",&p1->data);//不太安全(简略写法) 
			getchar();
			p1->front=first;
			first->back=p1;
			p1->back=p2;
			p2->front=p1;
			p2=p1;
		}
		i--;//每成功建立一个节点计时器i减一 
	} 
	//////////////////////////////////元素的打印
	printf("n=%d\n",n);
	p=first;
	while(p->back!=NULL) 
	{
		p1=p->back;
		printf("%d\n",p1->data);
		p=p->back;
	}
//	///////////////////////////////
//	// 节点的插入;
//	p1=first;
//	scanf("%d",&i);
//	getchar();
//	if(i<1||i>=n)
//	return -1;
//	p=(struct linklist *)malloc(SIZE);
//	scanf("%d",&p->data);//为插入节点data写入数据 
//	p->front=NULL;
//	p->back=NULL;
//	 while(i--)
//	 {
//	 	p1=p1->back;
//	 	p2=p1->back;
//	 }//需要插入在p1与p2之间 
//	 p->front=p1;
//	 p1->back=p;
//	 p2->front=p;
//	 p->back=p2;
//	 n++;
//	 /////////////////////////////////////////////////元素的打印 
//	printf("n=%d\n",n);
//	p=first;
//	while(p->back!=NULL) 
//	{
//		p1=p->back;
//		printf("%d\n",p1->data);
//		p=p->back;
//	}
	 
////////////////////////////////////////////////////////////////////////////////
// 节点的删除
scanf("%d",&i);
getchar();
if(i<1&&i>=n){
	return -1;
}
p1=first;
i--;
while(i--){       //i与p是第几个节点关系非常重要
	p1=p1->back;  
	p=p1->back;
	p2=p->back;
	
}//找到p1与p2节点下一步删除p节点
//p1与p2的链接删除p
p1->back=p2;
p2->front=p1;//连接成功
n--;
///////////////////////////////////////////
//元素的打印
 	 /////////////////////////////////////////////////元素的打印 
	printf("n=%d\n",n);
	p=first;
	while(p->back!=NULL) 
	{
		p1=p->back;
		printf("%d\n",p1->data);
		p=p->back;
	}
return 0;
	
}
发布了26 篇原创文章 · 获赞 0 · 访问量 94

猜你喜欢

转载自blog.csdn.net/qq_45812941/article/details/104413221