//main.c
#include <stdio.h>
#include <stdlib.h>
#include "DoublyLinkedList.h"
int main(void)
{
int choice;
DLL dll;
Init(&dll);
Create(&dll);
while (1)
{
printf("please enter your choice:\n");
scanf("%d", &choice);
switch(choice)
{
case 1:Insert(&dll);break;
case 2:Delete(&dll);break;
case 3:Traverse(&dll);break;
case 4:ReverseTraverse(&dll);break;
case 0:exit(0);break;
}
}
Destroy(&dll);
return 0;
}
//DoublyLinkedList.h
#define OK 1
#define ERROR 0
typedef int Status;
typedef int ElemType;
typedef struct DoublyLinkedList
{
ElemType data;
struct DoublyLinkedList *prior;
struct DoublyLinkedList *next;
}DoublyLinkedList,*DLinkedList;
//具有头结点的双向链表
typedef struct DLL
{
DLinkedList head;
int length;
}DLL;
//初始化
Status Init(DLL*);
//建立
Status Create(DLL*);
//插入
Status Insert(DLL*);
//删除
Status Delete(DLL*);
//遍历
Status Traverse(DLL*);
//反向遍历
Status ReverseTraverse(DLL*);
//销毁
Status Destroy(DLL*);
//DoublyLinkedList.c
#include "DoublyLinkedList.h"
#include <stdlib.h>
#include <stdio.h>
Status Init(DLL *dll)
{
dll->head = (DLinkedList)malloc(sizeof(DoublyLinkedList));
//如果没有申请到内存,则返回
if (!(dll->head))
{
return ERROR;
}
dll->head->prior = dll->head->next = dll->head;
dll->length = 0;
return OK;
}
Status Create(DLL *dll)
{
int i;
DLinkedList p, q;
p = dll->head;
printf("please enter length:\n");
scanf("%d", &(dll->length));
for (i = 0; i < dll->length; ++i)
{
q = (DLinkedList)malloc(sizeof(DoublyLinkedList));
if (!q)
{
return ERROR;
}
printf("please enter data:\n");
scanf("%d", &(q->data));
q->next = dll->head;
dll->head->prior = q;
q->prior = p;
p->next = q;
p = q;
}
return OK;
}
Status Insert(DLL *dll)
{
int position;
DLinkedList p = dll->head, q;
int i = 1;
printf("please enter position:\n");
scanf("%d", &position);
if (position < 1 || position > dll->length)
{
return ERROR;
}
while (i <= position)
{
++i;
p = p->next;
}
q = (DLinkedList)malloc(sizeof(DoublyLinkedList));
if (!q)
{
return ERROR;
}
printf("please enter data:\n");
scanf("%d", &(q->data));
//注意顺序
q->next = p;
q->prior = p->prior;
p->prior->next = q;
p-> prior = q;
++dll->length;
return OK;
}
Status Delete(DLL *dll)
{
int position;
DLinkedList p = dll->head;
int i = 1;
printf("please enter position:\n");
scanf("%d", &position);
if (position < 1 || position > dll->length)
{
return ERROR;
}
while (i <= position)
{
++i;
p = p->next;
}
p->prior->next = p->next;
p->next->prior = p->prior;
free(p);
--dll->length;
return OK;
}
Status Traverse(DLL *dll)
{
DLinkedList p =dll->head->next;
while (p != dll->head)
{
printf("%d\n", p->data);
p = p->next;
}
return OK;
}
Status ReverseTraverse(DLL *dll)
{
DLinkedList p =dll->head->prior;
while (p != dll->head)
{
printf("%d\n", p->data);
p = p->prior;
}
return OK;
}
Status Destroy(DLL *dll)
{
DLinkedList p = dll->head;
DLinkedList q = NULL;
while (p)
{
q = p->next;
free(p);
p = q;
}
return OK;
}
双向链表
最新推荐文章于 2024-07-29 17:54:45 发布