使用链接列表中的模板
Using template in linked list
我遇到了这个问题,我需要实现一个链表,但节点中存储的元素的数据类型可能是字符串或指向另一个类的指针
class Node{
public:
string data;
void *link;
Node *next;
Node(){
link = next = NULL;
}
Node(string str){
data = str;
}
Node(void *ptr){
link = ptr;
}
};
class List{
Node *head;
Node *tail;
public:
void insert(string str){
Node *newNode = new Node(str);
/* ... */
}
void insert(void *ptr){
Node *newNode = new Node(ptr);
/* ... */
}
};
我试着使用模板,但我做不到,我怎么能使用模板呢?
STL有一个std::list
模板类,你真的应该使用它。但如果你想实现自己的类,那么试试这样的方法:
template<typename T>
class Node
{
public:
Node *next;
T data;
Node(const T &value)
: next(NULL), data(value)
{
}
};
template<typename T>
class List
{
private:
Node<T> *head;
Node<T> *tail;
public:
List()
: head(NULL), tail(NULL)
{
}
void insert(const T &value)
{
Node<T> *newNode = new Node<T>(value);
if (!head)
head = newNode;
if (tail)
tail->next = newNode;
tail = newNode;
}
};
您可能会做这样的事情:
template <class T>
class List
{
public:
List(): root(NULL) {};
~List();
bool add(const T& item);
....
private:
typedef struct Node {
T item;
struct Node *next;
} Node;
Node *root;
};
如果能看到这个问题的其他答案,那将是一件有趣的事情。C++不是我最感兴趣的主题,但这个例子应该编译并运行。您知道,在C++中,struct是一种"默认情况下为public"的类,因此您甚至可以在其中包含函数(不过,我宁愿将私有函数添加到列表中)。
相关文章:
- 从链接列表c++中删除一个项目
- 读取文件的最后一行并输入到链接列表时出错
- 下面是我为检测链接列表中的循环而制作的代码
- 有人能帮我处理这个链接列表吗?C++
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 链接列表运算符重载没有打印出我想要的内容
- 链接列表在 cpp 中包含不同的对象类
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 如何在构建链接列表时调整头、尾指针
- Shared_ptr双链接列表内存泄漏
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 在链接列表中查找元素 - C++
- 删除链接列表中剩余的最后一个节点
- 只有我的"链接列表"中的第一个节点正在打印
- 避免在使用链接列表从 deque 中删除最后一个节点时出现内存泄漏
- C++ 分段错误:11 错误,同时编码将两个数字相加的链接列表
- 如何在C / C++中正确实现链接列表而不会使程序崩溃
- 将元素插入链接列表