代码实现—双链表
#include<iostream>
#include<stdlib.h>
using namespace std;
typedef int ElemType;
typedef struct Dnode{
ElemType data;
struct Dnode * prior;
struct Dnode * next;
}Dnode,*DLinkList;
bool InitDLinkList(DLinkList &L) {
L=(Dnode *)malloc(sizeof(Dnode)) ;
if(L==NULL)return false;
L->prior=NULL;
L->next=NULL;
return true;
}
bool InsertByNextNode(Dnode *p,Dnode *s){
if(p==NULL||s==NULL) return false;
s->next=p->next;
if(p->next!=NULL)
p->next->prior=s;
s->prior=p;
p->next=s;
return true;
}
bool DListInsert(DLinkList &L, int i,ElemType e){
if(i<1) {
cout<<"插入的位置有误!"<<endl;
return false;
}
Dnode *p=L,*s;
int j=0;
while(p!=NULL&&j<i-1){
p=p->next;
j++;
}
s=(Dnode *)malloc(sizeof(Dnode)) ;
s->data=e;
InsertByNextNode(p,s);
}
DLinkList CreateDList(DLinkList &L) {
L=(Dnode *)malloc(sizeof(Dnode));
if(L!=NULL){
L->prior=NULL;
L->next=NULL;
}
Dnode *s, *r=L;
int x;
cin>>x;
while(x!=9999){
s=(Dnode *)malloc(sizeof(Dnode));
s->data=x;
r->next=s;
s->prior=r;
r=s;
cin>>x;
}
r->next=NULL;
return L;
}
void PrintByOrderASC(DLinkList &L){
Dnode *p=L->next;
while(p){
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
void PrintByOrderDESC(DLinkList &L){
Dnode *p=L;
while(p->next!=NULL){
p=p->next;
}
while(p!=L){
cout<<p->data<<" ";
p=p->prior;
}
cout<<endl;
}
bool DeleteNextDnode(Dnode *p){
if(p==NULL)return false;
Dnode *q=p->next;
if(q==NULL)
return false;
p->next=q->next;
if(q->next!=NULL)
q->next->prior=p;
free(q) ;
return true;
}
void DestoryDList(DLinkList &L){
while(L->next!=NULL){
DeleteNextDnode(L);
}
free(L) ;
L=NULL;
}
bool DListDelete(DLinkList &L,int i,ElemType &e){
if(i<1) {
cout<<"删除结点有误!" <<endl;
return false;
}
Dnode *p=L;
int j=0;
while(p!=NULL&&j<i-1) {
p=p->next;
j++;
}
if(p==NULL)return false;
Dnode *q=p->next;
if(q==NULL)
return false;
p->next=q->next;
if(q->next!=NULL)
q->next->prior=p;
e=q->data;
free(q) ;
return true;
}
int main(){
DLinkList L;
InitDLinkList(L);
CreateDList(L);
PrintByOrderASC(L);
cout<<"在第3个位置插入3:";
DListInsert(L,3,3);
PrintByOrderASC(L);
int e;
DListDelete(L,5,e);
cout<<"删除第五个结点,第五个结点的值为:"<<e<<endl;
cout<<"顺序输出最后结果为:";
PrintByOrderASC(L);
cout<<"逆序输出最后结果为:";
PrintByOrderDESC(L);
}
运行结果:
1 2 3 4 5 9999
1 2 3 4 5
在第3个位置插入3:1 2 3 3 4 5
删除第五个结点,第五个结点的值为:4
顺序输出最后结果为:1 2 3 3 5
逆序输出最后结果为:5 3 3 2 1