【面试题】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();
}
相关推荐
小书房13 小时前
Kotlin的内联函数
java·开发语言·kotlin·inline·内联函数
码农阿豪13 小时前
Python 操作金仓数据库的完全指南(上篇):连接管理与高可用
开发语言·数据库·python
王老师青少年编程13 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【反悔贪心】:建筑抢修
c++·算法·贪心·反悔贪心·csp·信奥赛·建筑抢修
xyq202413 小时前
CSS Backgrounds(背景)
开发语言
缘如风13 小时前
Mongoose跨域解决方法
c++
Aurorar0rua13 小时前
CS50 x 2024 Notes C - 06
开发语言·学习方法
xyq202413 小时前
SQLite Like 子句详解
开发语言
Highcharts.js13 小时前
线形比赛积分增长或竞赛图|Highcharts企业图表代码示列
开发语言·前端·javascript·折线图·highcharts·竞赛图
古城小栈13 小时前
rust 亿级并发模型,实践完成
开发语言·网络·rust
Codigger官方14 小时前
Phoenix 语言起步指南:开启 Polyglot Singularity 之门
开发语言·人工智能·程序人生