这次我没有问题,但我只是在寻找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;
}
答案 0 :(得分:4)
基本列表实现通常称为单链表(或在函数式语言集合列表中)。
功能定义直接切入列表结构:
List := Empty | Cons T List
当然,这在C或C ++中确实不起作用,所以我们需要将结构切成两半:
以下是一些简单的代码:
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)
正如艾克斯所说,你最好的选择就是选择......
Of course, cplusplus.com has reference information on both.
作为STL的一部分,两个列表实现都经过了广泛的测试,调试和调试。两者都支持标准STL算法。几乎没有理由不使用它们。