本文主要介绍双向链表的构造以及基本操作
头文件
#ifndef double_H_
#define double_H_
struct dnode;
typedef struct dnode *dlist_point;
typedef dlist_point Dlist;
typedef dlist_point Position;
//插入函数
void Insert1(Dlist L,Position P,int X);
void Insert2(DList L,int Index,int X);
//删除函数
void Delete1(Dlist L,Position P);
void Delete2(Dlist L,int Index);
//遍历函数
void traverse(Dlist L);
#endif // double_H
双向链表的定义以及相应操作定义
#include <stdio.h>
#include <stdlib.h>
#include "main.h"
struct dnode
{
int element;
Position pre;
Position next;
};
//插入函数,P就是L中的一个节点
void Insert1(Dlist L,Position P,int X)
{
Position tem=L=malloc(sizeof(struct dnode));
if(tem==NULL)
{
printf("memory is not enough\n");
exit(1);
}
tem->pre=P;
tem->next=P->next;
P->next=tem;
tem->next->pre=tem;
}
//在链表的第Index位置上插入
void Insert2(Dlist L,int Index,int X)
{
Position P=L;
Position tem=malloc(sizeof(struct dnode));
int ind=0;
int suc=0;
while(P->next!=NULL)
{
if(ind==X-1)
{
tem->pre=P;
tem->next=P->next;
P->next->pre=tem;
P->next=tem;
tem->element=X;
suc=1;
printf("insert success\n");
break;
}
else
{
ind=ind+1;
P=P->next;
}
}
if(suc==0)
printf("the dlist do not have this position");
}
//删除函数
void Delete1(Dlist L,Position P)
{
Position tem=P->next->next;
tem->pre=P;
P->next=tem;
}
//删除第i个位置上的元素
void Delete2(Dlist L,int Index)
{
Position P=L;
int ind=0,suc=0;
while(P->next!=NULL)
{
if(ind==Index)
{
P->pre->next=P->next;
P->next->pre=P->pre;
suc=1;
printf("delete success");
break;
}
ind=ind+1;
P=P->next;
}
if(suc==0)
printf("this list do not have this position");
}
//遍历
void traverse(Dlist L)
{
Position P=L->next;
printf("dlist is\n");
while(P->next!=NULL)
{
printf("%d\n",P->element);
P=P->next;
}
}
主程序
int main()
{
Dlist head=malloc(sizeof(struct dnode));
Position tail=malloc(sizeof(struct dnode));
head->next=tail;
head->pre=NULL;
tail->pre=head;
tail->next=NULL;
Insert2(head,1,1);
Insert2(head,2,2);
Insert2(head,3,3);
Insert2(head,4,4);
traverse(head);
Delete2(head,2);
traverse(head);
return 0;
}