双向链表

代码示例:

//双向链表,初始化+尾插法

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

typedef struct Node pNode;
typedef struct Node
{
	int data;
	pNode *prev,*next;
};

//初始化链表,尾插法
pNode *InitList(pNode **head,int n)
{
	pNode *p,*s;
	(*head)=(pNode*)malloc(sizeof(pNode));
	if((*head)==NULL)
		exit(0);
	(*head)->next=NULL;//head的prev和next均指向NULL
	(*head)->prev=NULL;
	p=(*head);//p指向head
	int i;
	for(i=0;i<n;++i)
	{
		s=(pNode*)malloc(sizeof(pNode));
		if(s==NULL)
			exit(0);
		printf("input the value of the %dth node:",i+1);
		scanf("%d",&s->data);
		s->next=NULL;
		p->next=s;
		s->prev=p;
		p=s;//p指向尾节点
	}
	return p;
}

/*遍历打印*/
void PrintList(pNode *head)
{
	pNode *p;
	p=head->next;
	if(head->next==NULL)
		printf("the list is empty\n");
	while(p!=NULL)
	{
		printf("%d ",p->data);
		p=p->next;
	}
	printf("\n");
}
/*清空链表*/
void DeleteList(pNode **head)
{
	pNode *p;
	while((*head)->next !=NULL)
	{
		p=(*head);
		p->next->prev=NULL;
		(*head)=p->next;
		free(p);
	}
}

/*查找链表内的某个值*/
int SearchList(pNode *head)
{
	int number;
	printf("Values are aboout to be deleted:");
	scanf("%d",&number);
	pNode *p;
	while(p!=NULL)
	{
		if(p->data == number)
			return number;
		p=p->next;
	}
	return 0;
}

//删除链表中某个元素,令p的前驱节点和后驱节点相互指向即可,如果p是尾节点则直接将前驱节点指向NULL
void DelNumqList(pNode **head,int n)
{
	int i;
	pNode *p;
	p=(*head)->next;
	while(1)
	{
		if(p>data == n)
			break;
		p=p->next;
	}
	if(p->next==NULL)
	{
		p->prev->next=NULL;
		free(p);
	}
	else
	{
		p->next->prev=p->prev;
		p->prev->next=p->next;
		free(p);
	}
}

int main(int argc,char const *argv[])
{
	int n,element,flag;
	pNode *head,*last;
	printf("Please input the sizeof the list:");
	scanf("%d",&n);
	last=InitList(&head,n);//初始化链表并赋值,并返回尾节点last
	printf("%d %d\n",head->next->data,last->data);//打印第一个元素和最后一个元素
	PrintList(head);
	
	flag=SearchList(head);//搜索某个值并删除节点
	if(flag!=0)
	{
		DelNumqList(&head,flag);
		PrintList(head);
	}
	else
		printf(Element does not exist,can't be deleted\n);
	
	DeleteList(&head);//清空链表
	PrintList(head);
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值