列出C++中的实现

List implementation in C++

本文关键字:实现 C++ 列出      更新时间:2023-10-16

这次我没有问题,但我只是在寻找List实现,只是一个包含Node(int,nextNode)等节点的简单列表。我过去做过很多次,但我的 c++ 有点生疏。你能和我分享一下吗?我正在github上查找我的档案,但我没有找到antyhing。

编辑:

*我决定做我的,我不明白为什么使用删除后我仍然可以得到cout<getWrt()><*>

#include <cstdio>
#include <cmath>
#include<iostream>
using namespace std;
class Node{
public:
    Node(Node* next, int wrt){
        this->next = next;
        this->wrt = wrt;
    }
    Node(const Node& obiekt){
        this->wrt = obiekt.wrt;
        this->next = obiekt.next;
    }
    ~Node(){}
    void show(){
        cout<<this->wrt<<endl;
    }
    int getWrt(){
        return this->wrt;
    }
    Node* getNext(){
        return this->next;
    }
 private:
    Node* next;
    int wrt;
};

int main()
{
Node* n  = new Node(NULL, 2);
n->show();
Node* n2 = new Node(*n);
n2->show();
delete n;
n->show();
n2->show();
return 0;
}

基本的列表实现通常被称为单链表(或在函数式语言中称为 cons-list)。

功能定义直接切入列表的结构:

List := Empty | Cons T List

当然,这在 C 或 C++ 中并不真正有效,因此我们需要将结构一分为二:

  • 该列表实现为节点链
  • List 类隐藏此实现详细信息

下面是一些简单的代码:

template <typename T>
struct Node {
    Node(T t): element(t) {}
    T element;
    std::unique_ptr<Node> next;
};
template <typename T>
class List {
    typedef Node<T> N;
public:
    List() {}
    bool empty() const { return head == nullptr; }
    T& front() { assert(!this->empty()); return head->elem; }
    T const& front() const { { assert(!this->empty()); return head->elem; }
    void pop() { assert(!this->empty()); swap(head, head->next); }
    void push(T t) {
        std::unique_ptr<N> n{ new Node {t} };
        n->next = std::move(head);
        head = std::move(n);
     }
private:
    std::unique_ptr<N> head;
};

如您所见,此列表只是作为堆栈实现的,没有迭代等......尽管如此,这仍然是一个良好的开端:)

正如 aix 所说,你最好的选择是选择......

  • std::list,这是一个双向链表,这意味着它用向后遍历速度换取内存使用
  • 不太广泛实现的std::slist(在C++11中称为forward_list),它是单链接的,只能以一种方式遍历。

当然,cplusplus.com 两者都有参考信息。

作为 STL 的一部分,这两个列表实现都经过了广泛的测试、调优和调试。两者都支持标准的 STL 算法。几乎没有理由不使用它们。