#include<iostream>
#include<stdlib.h>
using namespace std;
#define ElemType int
// the discrepancy between linear list and double linked list is the pointer,
// the double linked have two pointers that the first is prior that make visit front
// other is next which can visit behind
typedef struct DNode{
ElemType data;
struct DNode *prior,*next;
}DNode,*DLinkList;
// init the list
DLinkList InitList(DLinkList &L)
{
L=new DNode;
L->prior=NULL;
L->next=NULL;
L->data=1;
DLinkList p=L;
for(int i=2;i<=5;i++)
{
DNode *body =new DNode;
body->prior=NULL;
body->next=NULL;
body->data=i;
p->next=body;
body->prior=p;
p=p->next;
// body->next=p->next;
// p->next->prior=body;
// body->prior=p;
// p->next=body;
// cout<<body->data;
}
return (L,p);
}
// insert the node
DLinkList Forward_Insert(DLinkList &L,int position,ElemType x)
{
DLinkList p=L;
int i=0;
if(position<0)
return L;
while(p&&position>(i+1))
{
p=p->next;
i++;
}
DNode *body =new DNode;
body->prior=NULL;
body->next=NULL;
body->data=x;
body->next=p->next;
p->next->prior=body;
body->prior=p;
p->next=body;
return L;
}
//delete this node
DLinkList Delete(DLinkList &L,ElemType x)
{
DNode *p,*q;
p=L;
while(p)
{
if(p->next->data==x){
break;
}
p=p->next;
}
q=p->next;
p->next=q->next;
q->next->prior=p;
free(q);
}
// from the end to the start
void Print_Prior_List(DLinkList L)
{
DLinkList p=L;
while(p)
{
printf("%d\n",p->data);
p=p->prior;
}
}
// from the start to the end
void Print_Next_List(DLinkList L)
{
DLinkList p=L;
while(p)
{
printf("%d\n",p->data);
p=p->next;
}
}
int main()
{
DLinkList L,R;
L,R=InitList(L);
Forward_Insert(L,3,9);
Delete(L,9);
Print_Prior_List(R);
return 0;
}
c++数据结构实现双向链表
最新推荐文章于 2022-12-04 22:44:25 发布