gpt4 book ai didi

c++ - 双向链表默认类型名节点

转载 作者:行者123 更新时间:2023-11-27 22:57:26 25 4
gpt4 key购买 nike

我正在编写一个简单的双向链表,如下所示:

节点.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();而不是必须提供模板参数?

最佳答案

"Since my list already knows the type T is there a possible implementation of First() and Last() where I can just do Node* node = testList.First(); or Node* end = testList.Last(); ?"

不,你不能,但你可以使用 auto 关键字,让编译器推断出实际类型:

    auto node = testList.First();
// ^^^^

do{
cout << "value of node : " << node->Source() << endl;
} while (node = node->Next());

关于c++ - 双向链表默认类型名节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31371698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com