基本模板链表
Basic template linked list
本文关键字:链表 更新时间:2023-10-16
#include <iostream>
#include <string>
using namespace std;
template <class T>
class Node{
friend class LinkedList<T>;
private:
T data;
Node <T> *next;
public:
Node();
Node(T d);
~Node();
};
template <class T>
Node<T>::Node(){
T data = 0;
next = 0;
}
template <class T>
Node<T>::Node(T d){
data = d;
next = 0;
}
template<class T>
Node<T>::~Node(){
delete next;
}
template <class T>
class LinkedList{
private:
Node <T> *head;
public:
LinkedList();
~LinkedList();
void Push_Front(const T& e);
}
template<class T>
LinkedList <T>::LinkedList(){
head = 0;
}
template <class T>
LinkedList<T>::~LinkedList(){
delete head;
}
template <class T>
void LinkedList<T>::Push_Front(const T &e){
Node<T> *newNode = new Node<T>(e);
if(head == 0)
head = new Node<T>(e);
newNode->next = head;
head = newNode;
}
void main(){
LinkedList<int> list;
list.Push_Front(10);
int t;
cin>>t;
return ;
}
我正在尝试编写链表的模板版本。我遇到了一些错误,不知道为什么。当我尝试使友元类 LinkedList 时发生错误,我需要这样做,以便我可以从 LinkedList 访问 T 数据。
: error C2059: syntax error : '<'
: see reference to class template instantiation 'Node<T>' being compiled
: error C2238: unexpected token(s) preceding ';'
: error C2143: syntax error : missing ';' before 'template'
: error C2989: 'LinkedList' : class template has already been declared as a non-class template
: see declaration of 'LinkedList'
: 'LinkedList': multiple template parameter lists are not allowed
: error C2988: unrecognizable template declaration/definition
: error C2059: syntax error : '<'
: error C2588: '::~LinkedList' : illegal global destructor
: fatal error C1903: unable to recover from previous error(s); stopping compilatio
您在类定义的末尾缺少分号LinkedList
。但是,即使您修复了这个问题,由于Node<T>
需要了解LinkedList<T>
,反之亦然,因此您需要在顶部声明它们:
#include <iostream>
#include <string>
using namespace std;
template <typename T> class Node;
template <typename T> class LinkedList;
//Code as before
相关文章:
- 反向给定链表中的K节点
- 如果没有malloc,链表实现将失败
- 文本文件中的单词链表
- 努力将整数转换为链表。不知道我在这里做错了什么
- 链表,反向函数,数据结构
- 使用std::list创建循环链表
- 链表的泛型函数remove()与成员函数remove)
- 为什么不能修改对象中的值?另外,我如何改进此链表?
- 我们可以删除链表中静态内存中的节点吗
- C++,指针数组,指向双链表中的条目
- 链表中写入访问冲突的未知原因
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 打印所有链表的元素 (C++)
- 错误:需要类名(链表c++)
- 为什么C中的通用链表中存储的数据已损坏
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 链表c++插入,所有情况都已检查,但没有任何工作
- 链表,将列表复制到另一个列表
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- 对单向链表进行排序时出现运行时错误