【面试题】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();
}
相关推荐
朝新_2 小时前
【多线程初阶】阻塞队列 & 生产者消费者模型
java·开发语言·javaee
立莹Sir2 小时前
Calendar类日期设置进位问题
java·开发语言
木子.李3473 小时前
排序算法总结(C++)
c++·算法·排序算法
风逸hhh3 小时前
python打卡day46@浙大疏锦行
开发语言·python
火兮明兮3 小时前
Python训练第四十三天
开发语言·python
freyazzr4 小时前
C++八股 | Day2 | atom/函数指针/指针函数/struct、Class/静态局部变量、局部变量、全局变量/强制类型转换
c++
ascarl20104 小时前
准确--k8s cgroup问题排查
java·开发语言
fpcc5 小时前
跟我学c++中级篇——理解类型推导和C++不同版本的支持
开发语言·c++
莱茵菜苗5 小时前
Python打卡训练营day46——2025.06.06
开发语言·python
爱学习的小道长5 小时前
Python 构建法律DeepSeek RAG
开发语言·python