【面试题】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();
}
相关推荐
handler0124 分钟前
从零实现自动化构建:Linux Makefile 完全指南
linux·c++·笔记·学习·自动化
Ulyanov29 分钟前
《PySide6 GUI开发指南:QML核心与实践》 第二篇:QML语法精要——构建声明式UI的基础
java·开发语言·javascript·python·ui·gui·雷达电子对抗系统仿真
码界筑梦坊32 分钟前
357-基于Java的大型商场应急预案管理系统
java·开发语言·毕业设计·知识分享
anzhxu37 分钟前
Go基础之环境搭建
开发语言·后端·golang
yu85939581 小时前
基于MATLAB的随机振动仿真与分析完整实现
开发语言·matlab
赵钰老师1 小时前
【结构方程模型SEM】最新基于R语言结构方程模型分析
开发语言·数据分析·r语言
guygg881 小时前
利用遗传算法解决列车优化运行问题的MATLAB实现
开发语言·算法·matlab
gihigo19981 小时前
基于MATLAB实现NSGA-III的土地利用空间优化模型
开发语言·matlab
vastsmile2 小时前
(R)26.04.23 hermes agent执行本地命令超级慢的原因
开发语言·elasticsearch·r语言
我头发多我先学2 小时前
C++ 模板全解:从泛型编程初阶到特化、分离编译进阶
java·开发语言·c++