#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct Node{
int data;
struct Node *prior;
struct Node *next;
}Node;
void CreateRail(Node *head,int a[],int n){//输入链表头指针值,数组,长度
Node *s,*r=head;//定义两个临时结点,s用于每次创建,赋给链表中的r(rail)结点
for(int i=1;i<=n;i++){//逐个点插入
s=(Node*)malloc(sizeof(Node));//S指向新结点
s->data=a[i];//值赋给结点的data
r->next=s;//把这个结点赋给链表中的结点C
s->prior=r;//本函数中唯一一句与单链表不同
r=r->next;//r指向它的后继
}
r->next=NULL;//尾指针的next为空
}
Node* Search(Node *head,int x){//输入头结点及值X,输出值为X的结点
for(Node *p=head;p->next!=NULL;p=p->next)//从头结点起扫到尾结点
if(p->next->data==x)//如果下一结点的值就是X(要修改结点值在此处修改)
return p->next;//返回值为X的结点
return NULL;//找不到就返回NULL
}
int Delete(Node *p){//输入当前要删除的结点
if(p==NULL)//如果当前结点不存在
return 0;//返回0表示删除失败
else if(p->next==NULL){//当前结点为尾结点
p->prior->next=NULL;//当前结点的前驱指空
free(p);//释放要删除的结点空间
return 1;//返回1表示删除成功
}
else{//否则
p->prior->next=p->next;//当前结点的前驱的后继指向当前结点的后继
p->next->prior=p->prior;//当前结点的后继的前驱指向当前结点的前驱
free(p);//释放要删除的结点空间
return 1;//返回1表示删除成功
}
}
void Insert(Node *p,int x){//输入加入结点的前驱及新增结点的值
Node *s=(Node*)malloc(sizeof(Node));//创建新结点
s->data=x;//赋值
s->next=p->next;//赋后继
s->prior=p;//赋前驱
p->next=s;//更新链表
}
int main(){//本例程默认是有头结点的,即第一个结点不存值
int a[11]={0,1,3,5,7,9,2,4,6,8,10};//定义数组
//int n;cin>>n;for(int i=0;i<n;i++)cin>>a[i];
Node *head=(Node*)malloc(sizeof(Node));CreateRail(head,a,10);//创建头结点并用尾插法建表
for(Node *p=head;p->next!=NULL;p=p->next)cout<<p->next->data<<' ';cout<<endl;//观察链表
Node *tmp1=Search(head,9);Delete(tmp1);//删除链表中值为9的结点
Node *tmp2=Search(head,8);Insert(tmp2,11);//在值为8的结点后加入值为11的结点
Node *tmp3=Search(head,5);cout<<tmp3->prior->data<<' '<<tmp3->next->data<<endl;//输出值为3的结点的前驱与后继的值
for(Node *p=head;p->next!=NULL;p=p->next)cout<<p->next->data<<' ';cout<<endl;//观察链表
return 0;
}
/***output
1 3 5 7 9 2 4 6 8 10
3 7
1 3 5 7 2 4 6 8 11 10
***/
1基础-2双链表
最新推荐文章于 2021-11-13 15:08:18 发布