【面试题】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();
}
相关推荐
aramae6 分钟前
模拟实现memset()(C语言)
c语言·开发语言·后端
hetao173383717 分钟前
2026-09-18 hetao1733837 的刷题记录
c++·算法
wuyk55540 分钟前
【Socket 进阶之路】第 7 章 IO 多路复用 select & poll 完整实战|多 fd 监听、超时等待、优缺点横向对比
服务器·开发语言·网络·数据库·物联网
stolentime1 小时前
CSP-J2026第一轮试题(附答案解析、markdown源码)
c++·csp
船厂电气自动化ai大模型1 小时前
AI大模型与数学|第81天 课程:正交向量、正交基、格拉姆‑施密特(Gram‑Schmidt)正交化
开发语言·数据结构·人工智能·线性代数·机器学习
Rabitebla1 小时前
【Linux系统编程】 指令(二):一条路径是怎么定位到文件的
linux·c++·笔记·学习·算法
lv__pf2 小时前
seata【实战 msb】
java·开发语言·后端
点纭2 小时前
C 语言 第七章 常用函数(3)
c语言·开发语言·算法·oracle·c#
程序员老陆2 小时前
std::experimental::when_any 深度解析:等待“第一个完成”的异步组合原语
c++·多线程
Rabitebla2 小时前
【Linux系统编程】指令(三):创建、删除、复制、移动、看内容
linux·数据结构·c++·算法