数据结构(C语言) -- 双循环链表demo

有头节点的双向循环链表

#include <stdio.h>
#include <stdlib.h>

typedef struct Node
{
    int data;
    struct Node *pre;
    struct Node *next;
} Node;

Node *initList()
{
    Node *DoubleLoopLink = (Node *)malloc(sizeof(Node));
    if (DoubleLoopLink == NULL)
    {
        printf("malloc DoubleLoopLink error!\n");
    }
    DoubleLoopLink->data = 0;
    DoubleLoopLink->pre = DoubleLoopLink;
    DoubleLoopLink->next = DoubleLoopLink;
    return DoubleLoopLink;
}

void headInsert(Node *DoubleLoopLink, int data)
{
    Node *newNode = (Node *)malloc(sizeof(Node));
    if (newNode == NULL)
    {
        printf("malloc newNode error!\n");
    }
    newNode->data = data;
    // 链表为空
    if (DoubleLoopLink->data == 0)
    {
        newNode->pre = DoubleLoopLink;
        newNode->next = DoubleLoopLink->next;
        DoubleLoopLink->next = newNode;
        DoubleLoopLink->pre = newNode;
    }
    else // 链表不为空
    {
        newNode->next = DoubleLoopLink->next;
        newNode->pre = DoubleLoopLink;
        DoubleLoopLink->next->pre = newNode;
        DoubleLoopLink->next = newNode;
    }
    DoubleLoopLink->data++;
}

void tailInsert(Node *DoubleLoopLink, int data)
{
    Node *newNode = (Node *)malloc(sizeof(Node));
    if (newNode == NULL)
    {
        printf("malloc newNode error!\n");
    }
    newNode->data = data;
    Node *current = DoubleLoopLink;
    while (current->next != DoubleLoopLink)
    {
        current = current->next;
    }
    newNode->pre = current;
    newNode->next = DoubleLoopLink;
    DoubleLoopLink->pre = newNode;
    current->next = newNode;

    DoubleLoopLink->data++;
}

void printList(Node *DoubleLoopLink)
{
    Node *head = DoubleLoopLink;
    Node *current = DoubleLoopLink->next;
    while (current != head)
    {
        printf("%-5d", current->data);
        current = current->next;
    }
    printf("\n");
    printf("剩余 %d 个节点\n", DoubleLoopLink->data);
}

void delete(Node *DoubleLoopLink, int data)
{
    Node *current = DoubleLoopLink->next;
    while (current != DoubleLoopLink)
    {
        if (current->data == data)
        {
            current->pre->next = current->next;
            current->next->pre = current->pre;
            free(current);
            DoubleLoopLink->data--;
            return;
        }
        current = current->next;
    }
}

int main(int argc, char const *argv[])
{
    Node *DoubleLoopLink = initList();
    for (int i = 0; i <= 100; i++)
    {
        tailInsert(DoubleLoopLink, i);
    }
    delete (DoubleLoopLink, 100);
    delete (DoubleLoopLink, 0);
    delete (DoubleLoopLink, 50);
    printList(DoubleLoopLink);
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值