列出C ++中的实现

时间:2012-05-26 17:07:42

标签: c++ list

这次我没有问题,但我只是在寻找List实现,只是一个包含Node(int,nextNode)等节点的简单List。我过去做过很多次但是我的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;
}

2 个答案:

答案 0 :(得分:4)

基本列表实现通常称为单链表(或在函数式语言集合列表中)。

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

List := Empty | Cons T List

当然,这在C或C ++中确实不起作用,所以我们需要将结构切成两半:

  • 该列表实现为Node
  • 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;
};

正如你所看到的,这个列表只是作为一个堆栈实现,没有迭代等......但是,这是一个很好的开始:)

答案 1 :(得分:2)

正如艾克斯所说,你最好的选择就是选择......

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

Of course, cplusplus.com has reference information on both.

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