【面试题】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();
}
相关推荐
编程版小新3 分钟前
C++初阶:STL详解(四)——vector迭代器失效问题
开发语言·c++·迭代器·vector·迭代器失效
c4fx22 分钟前
Delphi5利用DLL实现窗体的重用
开发语言·delphi·dll
鸽芷咕1 小时前
【Python报错已解决】ModuleNotFoundError: No module named ‘paddle‘
开发语言·python·机器学习·bug·paddle
Jhxbdks1 小时前
C语言中的一些小知识(二)
c语言·开发语言·笔记
java6666688881 小时前
如何在Java中实现高效的对象映射:Dozer与MapStruct的比较与优化
java·开发语言
Violet永存1 小时前
源码分析:LinkedList
java·开发语言
代码雕刻家1 小时前
数据结构-3.1.栈的基本概念
c语言·开发语言·数据结构
Fan_web1 小时前
JavaScript高级——闭包应用-自定义js模块
开发语言·前端·javascript·css·html
梦想科研社1 小时前
【无人机设计与控制】四旋翼无人机俯仰姿态保持模糊PID控制(带说明报告)
开发语言·算法·数学建模·matlab·无人机
风等雨归期1 小时前
【python】【绘制小程序】动态爱心绘制
开发语言·python·小程序