数据结构学习笔记(3)双向链表

完整代码

目录

DoubleList.h

DoubleList.c


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;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值