数据结构双向循环链表的C语言实现(插入,查询,删除),代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct DULNODE
{ int data; /*数据域*/
struct DULNODE *prior; /*指向前驱结点的指针域*/
struct DULNODE *next;/*指向后继结点的指针域*/
}DULNODE,*DuLinklist;
typedef int Elemtype;
DuLinklist Dulist_creat(DuLinklist L,int n)/*双向循环链表建立函数*/
{int i; DuLinklist p,r;
L=( DuLinklist)malloc(sizeof(DULNODE));/*为头结点分配空间*/
L->next=L->prior=L;
/*使头结点的后继指针和前驱指针都指向自身,形成空的双向循环链表*/
r=L; /*尾指针初始指向头结点*/
for (i=0;i<n;i++)
{ p=(DuLinklist)malloc(sizeof(DULNODE));/*为一个新结点分配空间*/
// printf("\nplease input the node(end with 0):\n ");
scanf("%d",&p->data); /*从键盘输入值,并保存在新结点数据域中*/
p->next=r->next; /*新结点后继指针指向尾结点r的后继结点*/
p->prior=r; /*新结点的前驱指针指向尾结点r*/
r->next=p; /*尾结点的后继指针指向新结点*/
r=p; /*尾指针指向新结点,即新结点成为尾结点*/
}
L->prior=r; /*使尾结点成为头结点的前驱结点*/
return L;
}

#include <stdio.h>
#include <malloc.h>

typedef int Elemtype;

typedef struct dNode {
Elemtype data; /*数据域*/
struct dNode *prior; /*指向前驱结点的指针域*/
struct dNode *next;/*指向后继结点的指针域*/
}*pDLink,*DLinkList;

DLinkList GetEmptyDLink() { // 初始化
DLinkList head = (pDLink)malloc(sizeof(struct dNode));
head->data = 0;
head->prior = head;
head->next = head;
return head;
}

void DLink_create(DLinkList head,int n) { /*双向循环链表建立函数*/
int i; 
pDLink p,r;
p = r = head;
for(i = 0;i < n;i++) {
p->next = (pDLink)malloc(sizeof(struct dNode));/*为一个新结点分配空间*/
scanf("%d",&p->next->data); /*从键盘输入值,并保存在新结点数据域中*/
p = p->next; // p指向新结点
p->prior = r;// 新结点的prior指向上一个结点
r = r->next; // 上一个结点前进到新结点
}
p->next = head; // 指向头结点
head->prior = p;// head的prior指向最后的结点
}

void Show(DLinkList head) { // 正向显示链表数据
pDLink p = head->next;
while(p != head) {
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}

void ShowR(DLinkList head) { // 反向显示数据
pDLink p = head->prior;
while(p != head) {
printf("%d ",p->data);
p = p->prior;
}
printf("\n");
}

int main() {
DLinkList head = GetEmptyDLink();
DLink_create(head,10);
printf("正向显示:\n");
Show(head);
printf("反向显示:\n");
ShowR(head);
return 0;
}

温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答