双向链表的基本操作

#include<iostream>
#include<cmath>
#include<cstring>
using namespace std;
typedef long long ll;
typedef struct line
{
	int data;
	struct line *pre;//前指针
	struct line *next;//后指针
}line,*a;
line* init_line(line*head)
{
	cout<<"请输入双向链表的大小:";
	int size;
	cin>>size;
	if(size<1) return NULL;
	//申请空间与初始化
	head=(line*)malloc(sizeof(line));
	head->pre=NULL;
	head->next=NULL;
	cout<<"请输入头结点的数值大小:";
	int data;
	cin>>data;
	head->data=data;
	//赋值完头节点之后开始后续的节点的创建
	int pos=1;
	line *ls=head;
	while(pos<=size)
	{
		line *node=(line*)malloc(sizeof(line));
		node->pre=NULL;
		node->next=NULL;
		cout<<"请输入第"<<pos<<"结点的数值大小:";
		pos++;
		cin>>data;
		node->data=data;
		ls->next=node;
		node->pre=ls;
		ls=ls->next;
	}
	return head;
}
line *ls_insert(line*head,int pos,int data)
{
	//先初始化要添加的node
	//指针一定要置空
	line *node=(line*)malloc(sizeof(line));
	node->data=data;
	node->pre=NULL;
	node->next=NULL;
	//插入链表的表头
	if(pos==1)
	{
		node->next=head;
		head->pre=node;
		head=node;//此时head指针指向第一个位置
	}
	else
	{
		line *p=head;
		//指向插入位置的前一个位置
		for(int i=1;i<pos-1;i++)
		{
			p=p->next;
		}
		//如果此时指针不为空就代表不是最后一个
		if(p->next)
		{
			//需要有序替换四条线
			p->next->pre=node;
			node->next=p->next;
			p->next=node;
			node->pre=p;
		}
		//如果插入位置是表尾
		else
		{
			//相互连接就行
			p->next=node;
			node->pre=p;
		}
	}
	return head;
}
line *ls_delete(line *head,int data)
{
	//只要引用头节点指针即可
	line* ls=head;
	while(ls)
	{
		//遍历判断即可
		if(ls->data==data)
		{
			ls->pre->next=ls->next;
			ls->next->pre=ls->pre;
			free(ls);
			cout<<"已经成功删除!"<<endl;
			return head;
		}
		//没搜到就往下遍历即可
		ls=ls->next;
	}
}
void ls_display(line *head)
{
	line *ls=head;
	int pos=1;
	while(ls)
	{
		cout<<"第"<<pos<<"个数据是:"<<ls->data<<endl;
		pos++;
		ls=ls->next;
	}
}
int main()
{
	cout<<"**************************************"<<endl;
	cout<<"创建双链表操作"<<endl;
	line *head=NULL;
	head=init_line(head);
	ls_display(head);
	cout<<"**************************************"<<endl;
	cout<<"插入双链表操作"<<endl;
	head=ls_insert(head,2,40);
	ls_display(head);
	cout<<"**************************************"<<endl;
	cout<<"删除双链表操作"<<endl;
	head=ls_delete(head,40);
	ls_display(head);
	cout<<"**************************************"<<endl;
	cout<<"所有操作结束"<<endl;
	cout<<"**************************************"<<endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

温柔济沧海

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值