完整代码
目录
DoubleList.h
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef int DataType;
typedef struct Node
{
DataType data;
struct Node* next;
struct Node* prior;
}DLNode;
//初始化
void ListInitiate(DLNode** head);
//插入数据元素
int ListInsert(DLNode* head, int i, DataType x);
//删除数据元素
int ListDelete(DLNode* head, int i, DataType *x);
//求当前数据元素的个数
int ListLength(DLNode* head);
//撤销内存空间
void Destroy(DLNode** head);
DoubleList.c
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include"DoubleList.h"
//初始化
void ListInitiate(DLNode** head) {
*head = (DLNode*)malloc(sizeof(DLNode));
(*head)->prior = *head;
(*head)->prior = *head;
}
//插入数据元素
int ListInsert(DLNode* head, int i, DataType x) {
DLNode* p, * s;
int j;
p = head->next;
j = 0;
while (p->next != head && j < i){
//让p指向第i个结点
p = p->next;
j++;
}
if (j != i) {
printf("输入位置无效");
return 0;
}
s = (DLNode*)malloc(sizeof(DLNode));
s->data = x;
s->prior = p->prior;
p->prior->next = x;
s->next = p;
p->prior = x;
return 1;
}
//删除数据元素
int ListDelete(DLNode* head, int i, DataType *x) {
DLNode* p;
p = head->next;
int j = 0;
while (p->next != head && j < i) {
p = p->next;
j++;
}
if (j != i) {
printf("输入位置无效");
return 0;
}
*x = p->data;
p->prior->next = p->prior;
p->next->prior = p->next;
return 1;
}
//求当前数据元素的个数
int ListLength(DLNode* head) {
DLNode* p=head;
int size = 0;
while (p->next != head) {
p = p->next;
size++;
}
return size;
}
//撤销内存空间
void Destroy(DLNode** head) {
DLNode *p, *p1;
int i;
p = head;
for (i = 0; i <= ListLength(head); i++) {
p1 = p;
p = p->next;
free(p1);
}
*head = NULL;
}