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

该程序定义了一个双链表结构,实现了初始化、在头部插入、在尾部插入和删除指定数据的节点功能,并能打印链表内容。主要操作涉及动态内存分配和链表指针的更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有头节点的双链表

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

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

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

void headInsert(Node *DoubleLink, int data)
{
    Node *newNode = (Node *)malloc(sizeof(Node));
    if (newNode == NULL)
    {
        printf("malloc newNode error!\n");
    }
    newNode->data = data;

    if (DoubleLink->data == 0)
    {
        // 链表为空
        newNode->next = DoubleLink->next;
        newNode->pre = DoubleLink;
        DoubleLink->next = newNode;
        DoubleLink->data++;
    }
    else
    {
        newNode->pre = DoubleLink;
        newNode->next = DoubleLink->next;
        DoubleLink->next->pre = newNode;
        DoubleLink->next = newNode;
        DoubleLink->data++;
    }
}

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

    DoubleLink->data++;
}

void delete(Node *DoubleLink, int data)
{
    Node *current = DoubleLink->next;
    while (current->next != NULL)
    {
        if (current->data == data)
        {
            current->pre->next = current->next;
            current->next->pre = current->pre;
            free(current);
            DoubleLink->data--;
            return;
        }
        current = current->next;
    }
    // current 到了最后一个节点
    if (current->data = data)
    {
        current->pre->next = NULL;
        free(current);
        DoubleLink->data--;
    }
}

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

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值