【面试题】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();
}
相关推荐
一起养小猫9 分钟前
Flutter for OpenHarmony 实战:打造天气预报应用
开发语言·网络·jvm·数据库·flutter·harmonyos
安全二次方security²10 分钟前
CUDA C++编程指南(7.25)——C++语言扩展之DPX
c++·人工智能·nvidia·cuda·dpx·cuda c++编程指南
xyq202412 分钟前
Java 抽象类
开发语言
爱装代码的小瓶子14 分钟前
【c++与Linux基础】文件篇(4)虚拟文件系统VFS
linux·开发语言·c++
疯狂的喵5 小时前
C++编译期多态实现
开发语言·c++·算法
2301_765703146 小时前
C++中的协程编程
开发语言·c++·算法
m0_748708056 小时前
实时数据压缩库
开发语言·c++·算法
小魏每天都学习6 小时前
【算法——c/c++]
c语言·c++·算法
lly2024066 小时前
jQuery Mobile 表格
开发语言
惊讶的猫6 小时前
探究StringBuilder和StringBuffer的线程安全问题
java·开发语言