双向链表的源码实现

#include <iostream>
using namespace std;
typedef int ElmType;
const int length=10;

typedef struct node
{
	ElmType i;
	struct node* next;
	struct node* back;
}Node;

typedef Node* pNode;

void init(pNode&,int);  //初始化双链表
bool traverse(pNode);  //前后遍历双链表
void insert(pNode&,int);    //在节点p后插入
void del(pNode&);      //删除节点p
void collect_space(pNode head);

void main()
{
	pNode head,p;  //生成一个未初始化的Node类型头指针
	init(head,length);//建立双向链表,其中包括初始化head指针
	p=head->next->next;
	insert(p,1);
	traverse(head); //遍历
	getchar(); //按任意键退出
	collect_space(head);  //收回链表空间
}

void init(pNode &head,int max_num)
{
    head=(Node*)malloc(sizeof(Node));
	head->i=0;
	head->back=NULL;
	head->next=NULL;
	Node *p,*temp;
	p=head;
	for(int i=1;i<max_num;i++)
	{
		temp=(Node*)malloc(sizeof(Node));
		temp->i=i;
		temp->back=p;
		temp->next=NULL;
		p->next=temp;
		p=temp;
	}
}

bool traverse(pNode head)
{
	if(head==NULL)
	{
		cout<<"输入的head为空"<<endl;
		return false;
	}
	while(head!=NULL)
	{
		cout<<head->i<<"  ";
		head=head->next;
	}
	return true;
}

void del(pNode &p)
{
	if(p==NULL)
	{
		cout<<"你输入的指针为空"<<endl;
		return;
	}
	Node *temp=p;
	if(p->next==NULL)
	{
		//如果删除的是尾指针,那么删除p后,p所指向位置自动前移一位
		if(p->back==NULL)
		{
			cout<<endl<<"链表已清空"<<endl;
			free(p);
			p=NULL;
			return;
		}
		else
		{
		   p=temp->back;
		   p->next=NULL;
		   free(temp);
		}
	}
	else if(p->back==NULL)
	{
		//如果删除的是头指针,那么删除p后,p所指向位置向后移一位
		p=temp->next;
		p->back=NULL;
		free(temp);
	}
	else
	{
		//如果删除的是中间位置的,那么删除p后,p指向位置向前移一位
		p=temp->next;
		temp->back->next=p;
		p->back=temp->back;
		free(temp);
	}
}

void insert(pNode &p,int n)
{
	if(p==NULL)
	{
		cout<<"链表为空!"<<endl;
		return;
	}
	pNode temp=(pNode)malloc(sizeof(Node));
	temp->i=n;
	if(p->next==NULL)
	{
		p->next=temp;
		temp->next=NULL;
		temp->back=p;
	}
	else 
	{
        temp->next=p->next;
		temp->back=p;
		p->next->back=temp;
		p->next=temp;
	}
}

void collect_space(pNode head)
{
   while(head!=NULL)
   {
	   del(head);
   }
}




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值