【数据结构】6. 带头节点的双循环链表(完整代码实现初始化尾插、尾删、头插、头删、任意位置的插入、任意位置的删除、获取有效元素的大小、查找、销毁)

DCList.h

#pragma once

typedef int DataType;

typedef struct DListNode
{
    struct DListNode* next;
    struct DListNode* prev;
    DataType data;
}Node;


void DListInit(Node** head); 

void DListPushFront(Node* head, DataType data);
void DListPopFront(Node* head);

void DListPushBack(Node* head, DataType data);
void DListPopBack(Node* head);

void DListInsert(Node* pos, DataType data);
void DListErase(Node* pos);

void DListDestroy(Node** head);

DCList.c

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


#include "DCList.h"

Node* BuyDListNode(DataType data)
{
    Node* newNode = (Node*)malloc(sizeof(Node));
    if (NULL == newNode)
    {
        assert(0);
        return NULL;

    }

    newNode->data = data;
    newNode->next = NULL;
    newNode->prev = NULL;

    return newNode;

}

void DListInit(Node** head)
{
    assert(head);
    *head = BuyDListNode(0);
    (*head)->next = *head;
    (*head)->prev = *head;

}


void DListPushFront(Node* head, DataType data)
{
    DListInsert(head->next, data);

}

void DListPopFront(Node* head)
{
    assert(head);
    DListErase(head->next);

}

void DListPushBack(Node* head, DataType data)
{
    DListInsert(head, data);

}

void DListPopBack(Node* head)
{
    assert(head);
    DListErase(head->prev);

}

void DListInsert(Node* pos, DataType data)
{
    Node* newNode = NULL;
    if (NULL == pos)
        return;

    newNode = BuyDListNode(data);
    newNode->prev = pos->prev;
    newNode->next = pos;
    newNode->prev->next = newNode;
    pos->prev = newNode;

}

void DListErase(Node* pos)
{
    if (NULL == pos)
        return;

    pos->prev->next = pos->next;
    pos->next->prev = pos->prev;

    free(pos);

}

void DListDestroy(Node** head)
{
    assert(head);
    Node* cur = (*head)->next;
    while (cur != (*head))
    {
        (*head)->next = cur->next;
        free(cur);
        cur = (*head)->next;

    }

    free(*head);
    *head = NULL;

}

void TestDList(Node* head)
{
    assert(head);
    Node* cur = head->next;
    while (cur != head)
    {
        printf("%d ", cur->data);
        cur = cur->next;

    }
    printf("\n");

}

test.c

#include <stdio.h>

#include "DCList.h"

int main()
{
    Node* head = NULL;
    DListInit(&head);

    DListPushBack(head, 1);
    DListPushBack(head, 2);
    DListPushBack(head, 3);
    DListPushBack(head, 4);
    DListPushBack(head, 5);
    DListPushBack(head, 6);
    TestDList(head);

    DListPushFront(head, 0);
    TestDList(head);

    DListPopFront(head);
    TestDList(head);

    DListPopBack(head);
    DListPopBack(head);
    DListPopBack(head);
    TestDList(head);

    DListDestroy(&head);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值