数据结构四
一、关于线性表中双链表
#include "stdio.h"
#include "stdlib.h"
struct DNode{
int data;
struct DNode* prior,* next;
};
struct DNode* CreateNode(int e){
struct DNode* p=(struct DNode*) malloc(sizeof(struct DNode));
if(!p){
printf("No enough memory to allocate!\n");
exit(0);
}
p->data=e;
p->prior=NULL;
p->next=NULL;
return p;
}
//在p节点之后插入节点s
int InsertNextDNode(struct DNode* p,struct DNode* s){
if(p==NULL||s==NULL) return 0;
s->next=p->next;
if(p->next!=NULL)
p->next->prior=s;
s->prior=p;
p->next=s;
return 1;
}
//在p节点之后删除后继节点
int DeleteNextDNode(struct DNode* p){
struct DNode* q=NULL;
if(p==NULL) return 0;
q=p->next;//找到p节点的后继节点
p->next=q->next;
if(q->next!=NULL)
q->next->prior=p;
free(q);
return 1;
}
//遍历双链表
void ListDisplay(struct DNode* L){
struct DNode* p=L;
int j=0;
while (p!=NULL){
printf("The %dth node of Double-linked-list is %d\n",j,p->data);
j++;
p=p->next;
}
}
//销毁双链表
void DestroyList(struct DNode* L){
while (L->next!=NULL){
DeleteNextDNode(L);
}
free(L);
}
int main(){
struct DNode* p=NULL,*s=NULL;
//1.创建头指针,指向头节点
struct DNode* L= CreateNode(0);//创建带头节点的双链表
//2.循环遍历插入5个数据
p=L;
for (int i = 0; i < 5; i++) {
s= CreateNode(i*500+1);
InsertNextDNode(p,s);
p=p->next;
}
ListDisplay(L);
DestroyList(L);
return 0;
}
实现结果:
D:\project\clion\ch1\cmake-build-debug\other_linked_list.exe
The 0th node of Double-linked-list is 0
The 1th node of Double-linked-list is 1
The 2th node of Double-linked-list is 501
The 3th node of Double-linked-list is 1001
The 4th node of Double-linked-list is 1501
The 5th node of Double-linked-list is 2001
Process finished with exit code 0