#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;
}
双向链表的基本操作
最新推荐文章于 2024-10-11 16:56:17 发布