用c++实现单向链表和双向链表

本文详细介绍了链表这一基础数据结构,包括单向链表和双向链表的定义、创建、遍历及删除等核心操作,并提供了具体的实现代码。

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

链表是一种非常基础的数据结构,本身也比较灵活,突破了数组在一开始就要确定长度的限制,能够做到随时使用随时分配内存。同时还有添加,删除,查找等功能。

总的来说,链表是由几个模块构成的。
一,单向链表

//链表基本元素

struct Node
{
    int num;
    Node * next;
};

//创建节点

    Node * current=nullptr;
    Node * head=nullptr;//用以存放第一个节点,有了这么一个首节点后就相当于有了一个基点
    Node * pre=nullptr;
    int n;
    while (cin >> n, n != -1)//输入-1时结束创建链表
    {
        current = new Node;
        current->next = nullptr;
        current->num = n;
        if (head == nullptr)
            head = current;
        else
            pre->next = current;
        pre = current;
    }

//遍历节点

    current = head;
    while (current != nullptr)
    {
        cout << current->num << endl;
        current = current->next;
    }

//删除节点

    current = head;
    while (current != nullptr)
    {
        Node * temp;//如果先释放了current,那么current将无法指向它的下一个节点
        temp = current;
        delete temp;
        current = current->next;
    }

二,双向链表
双向链表相对于单向链表来说更为灵活方便,且实现起来也不是很难,在单向链表的基础上加上previous的指针就行了。
//基本元素

struct Node
{
int num;
Node * next;
Node * pre;
};

//具体实现

node * head=nullptr;
node * current=nullptr;
node * pre=nullptr;
while (cin >> n, n != -1)
{
current = new node;//先申请一块内存用以存放新的节点
current->next = nullptr;
current->pre = nullptr;
current->num = n;
if (head == nullptr)
head = current;//指针本质也不过是一种变量而已
else
{
current->pre = pre;
pre->next = current;
}
pre = current;//这里没有写成 current=current->next(之前就有犯了这种错),否则之后申请了新的内存之后指向就发生错误了
}
current->next = head;
head->pre = current;
current = head->pre;
while (current != head)
{
cout << current->num << endl;
current = current->pre;
}

current = head;
//int count = 0;
while (current != nullptr)
{
node * temp;
temp = current;
current = current->next;
delete temp;
//cout << ++count << endl;
}

以上只是链表的基本实现,关于如何实现其他一些功能,我们以后再谈。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值