双链表默认typename节点
Doubly Linked List default typename Node
我正在写一个简单的双链表,看起来像这样:
Node.h
#pragma once
template<typename T>
class Node
{
public:
Node() : _next(nullptr), _prev(nullptr) {}
Node(Node* next, Node* prev, T data) : _next(next), _prev(prev), _data(data) {}
Node* Next() { return _next; }
Node* Prev() { return _prev; }
T Source() { return _data; }
Node* _next;
Node* _prev;
T _data;
};
DLList.h
#include "Node.h"
template<typename T>
class DLList
{
public:
DLList() : _head(nullptr) {}
Node<T>* AddNode(T val)
{
Node<T>* m_prev = _head;
Node<T>* m_node = new Node<T>(nullptr, m_prev, val);
if (m_prev)
m_prev->_next = m_node;
_head = m_node;
return m_node;
}
Node<T>* First()
{
Node<T>* m_node = _head;
while (m_node->Prev()) { m_node = m_node->Prev(); }
return m_node;
}
Node<T>* Last()
{
return _head;
}
private:
Node<T>* _head;
};
现在我对它做了一些测试,它们都很好,测试如下:
#include "DLList.h"
using namespace std;
int main(int argc, char** argv)
{
DLList<int> testList;
for (int i = 0; i < 10; i++)
testList.AddNode(i * 10);
Node<int>* node = testList.First();
do{
cout << "value of node : " << node->Source() << endl;
} while (node = node->Next());
Node<int>* end = testList.Last();
do{
cout << "value of node : " << end->Source() << endl;
} while (end = end->Prev());
cin.get();
return 0;
}
我的问题是,每次我必须声明一个Node
指针来获得列表中的第一个或最后一个Node
,我必须这样做:Node<int>* end = testList.Last();
或Node<int>* node = testList.First();
。因为我的列表已经知道类型T
是否有First()
和Last()
的可能实现,我可以只做Node* node = testList.First();
或Node* end = testList.Last();
,而不必提供模板参数?
"由于我的列表已经知道类型
T
,是否有可能实现First()
和Last()
,我可以只做Node* node = testList.First();
或Node* end = testList.Last();
?"
不,你不能,但你可以使用auto
关键字,让编译器推断出实际类型:
auto node = testList.First();
// ^^^^
do{
cout << "value of node : " << node->Source() << endl;
} while (node = node->Next());
我个人不会直接暴露Node。
我将向类公开一个内部定义的Iterator
类型(如果碰巧是Node,那就好了)。
template<typename T>
class DLList
{
public:
DLList() : _head(nullptr) {}
typedef Node<T> iterator;
typedef Node<const T> const_iterator;
T& First(); // would not expose a node here.
T const& First() const;// I would return the first value in the list.
iterator begin(); // Iterator to first element.
const_iterator begin() const;
....
现在你可以使用auto技巧来防止你指定的东西太精确。
int main()
{
DLList<int> data;
// Add data.
auto it = data.begin();
相关文章:
- 反向给定链表中的K节点
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- Boost Graph Library,修复节点大小
- C++A*算法并不总是在路径中具有目标节点
- 如何找到2个单链表的公共节点
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 为什么我的删除节点函数实际上没有删除节点?
- 我们可以删除链表中静态内存中的节点吗
- 如何在pugixml中获取节点的内部XML
- 为什么我们要为avl树实现返回一个指向节点的指针,而不是void函数
- C++RapidXml-使用first_node()遍历以修改XML文件中节点的值
- 为什么返回类型中需要typename?C++
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- 节点 *temp; 和节点 *tmp = 新节点之间的差异
- 引擎节点:未定义的符号:_ZTV6Config
- 为什么"delete"关键字不删除节点?
- 如何使用发送数据包所花费的时间计算两个节点之间的距离?
- 如何按数字顺序插入链表节点?
- 双链表默认typename节点