【面试题】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();
}
相关推荐
fengfuyao9855 分钟前
基于MATLAB的GUI实现人脸检测、眼睛检测以及LBP直方图显示
开发语言·计算机视觉·matlab
蒋星熠9 分钟前
C++零拷贝网络编程实战:从理论到生产环境的性能优化之路
网络·c++·人工智能·深度学习·性能优化·系统架构
CHANG_THE_WORLD23 分钟前
# C++ 中的 `string_view` 和 `span`:现代安全视图指南
开发语言·c++
雨落倾城夏未凉23 分钟前
9.c++new申请二维数组
c++·后端
Franklin1 小时前
Python界面设计【QT-creator基础编程 - 01】如何让不同分辨率图像自动匹配graphicsView的窗口大小
开发语言·python·qt
雨落倾城夏未凉1 小时前
8.被free回收的内存是立即返还给操作系统吗?为什么?
c++·后端
雨落倾城夏未凉1 小时前
6.new和malloc的区别
c++·后端
郝学胜-神的一滴1 小时前
深入理解QFlags:Qt中的位标志管理工具
开发语言·c++·qt·程序人生
柯南二号2 小时前
【Java后端】MyBatis-Plus 原理解析
java·开发语言·mybatis
INS_KF2 小时前
【C++知识杂记2】free和delete区别
c++·笔记·学习