【面试题】c++实现简易单链表

cpp 复制代码
#include <iostream>
//实现单链表
class Node {
public:
    int data;
    Node* next;
    Node(int value) :data(value), next(nullptr) {}
};

class LinkedList
{
private:
    Node* head;

public:
    LinkedList() :head(nullptr) {}
    //添加元素在最后
    void appent(int value) {
        Node* new_node = new Node(value);
        if (!head) {
            head = new_node;
            return;
        }
        Node* current = head;
        while (current->next)
        {
            current = current->next;
        }
        current->next = new_node;
    }
    //显示函数
    void display() {
        Node* current = head;
        while (current)
        {
            std::cout << current->data << "->";
            current = current->next;
        }
        std::cout << "nullptr" << std::endl;
    }
    //删除一个特定节点
    void remove(int value) {
        if (!head) {
            return;
        }
        if (head->data == value) {
            Node* temp = head;
            head = head->next;
            delete temp;
        }
        Node* current = head;
        while (current->next)
        {
            if (current->data == value) {
                Node* temp = current->next;
                current->next = current->next->next;
                delete temp;
                return;
            }
            current = current->next;
        }
    }
    //查找
    bool search(int value) { 
        Node* current = head;
        while (current) {
            if (current->data == value) {
                return true;
            }
            current = current->next;
        }
        return false;
    }
    //清除
    void clear() {
        while (head) {
            Node* temp = head;
            head = head->next;
            delete temp;
        }
    }
    ~LinkedList() {
        clear();
    }
};


int main()
{
    LinkedList Mylist;
    Mylist.appent(1);
    Mylist.appent(2);
    Mylist.appent(3);
    Mylist.appent(4);
    Mylist.display();
    Mylist.remove(1);
    Mylist.display();
}
相关推荐
珊瑚里的鱼7 分钟前
第九讲 | 模板进阶
开发语言·c++·笔记·visualstudio·学习方法·visual studio
未来之窗软件服务17 分钟前
人体肢体渲染-一步几个脚印从头设计数字生命——仙盟创梦IDE
开发语言·ide·人工智能·python·pygame·仙盟创梦ide
Echo``25 分钟前
40:相机与镜头选型
开发语言·人工智能·深度学习·计算机视觉·视觉检测
摄殓永恒35 分钟前
猫咪几岁
数据结构·c++·算法
lisw0543 分钟前
R语言的专业网站top5推荐
开发语言·r语言
清同趣科研43 分钟前
扩增子分析|R分析之微生物生态网络稳定性评估之节点和连接的恒常性、节点持久性以及组成稳定性指数计算
开发语言·r语言
纨妙1 小时前
python打卡打印26
开发语言·python
.小墨迹1 小时前
Apollo学习——键盘控制速度
linux·开发语言·c++·python·学习·计算机外设
似水এ᭄往昔1 小时前
【数据结构】——队列
c语言·数据结构·c++·链表
烛九_阴1 小时前
【C++】解析C++面向对象三要素:封装、继承与多态实现机制
c++