所以我一直在研究一个带有节点结构的链表类。当我在类之前定义模板化结构时,类可以工作,但当它在类的私有部分中声明时,它不工作。我特别需要使用模板t在类私有部分中定义ListNode Struct。
#include <iostream>
using namespace std;
template <typename T>
class LinkedList
{
public:
LinkedList()
{
head = NULL;
tail = NULL;
numNodes = 0;
}
~LinkedList()
{
}
int getLength()
{
return numNodes;
}
T getNodeValue(int value)
{
ListNode<T> *indexNode;
indexNode = head;
int i = 0;
if (value < 0 || value > numNodes - 1)
{
throw;
}
while (indexNode->next != NULL)
{
if (i == value)
{
break;
}
indexNode = indexNode->next;
i++;
}
return indexNode->contents;
}
void insertNode(ListNode<T> *newNode)
{
if (head == NULL)
{
head = newNode;
tail = head;
tail->next = NULL;
numNodes++;
return;
}
if (newNode->contents <= head->contents)
{
if (head == tail)
{
head = newNode;
head->next = tail;
}
else
{
ListNode<T> *placeholder;
placeholder = head;
head = newNode;
head->next = placeholder;
}
numNodes++;
return;
}
if (newNode->contents > tail->contents)
{
if (head == tail)
{
tail = newNode;
head->next = tail;
}
else
{
ListNode<T> *placeholder;
placeholder = tail;
tail = newNode;
placeholder->next = tail;
}
numNodes++;
return;
}
ListNode<T> *indexNode;
indexNode = head;
while (indexNode->next != NULL)
{
if (newNode->contents <= indexNode->next->contents)
{
newNode->next = indexNode->next;
indexNode->next = newNode;
numNodes++;
return;
}
indexNode = indexNode->next;
}
}
private:
template <typename T>
struct ListNode
{
ListNode()
{
next = NULL;
}
ListNode(T value)
{
contents = value;
next = NULL;
}
T contents;
ListNode<T> *next;
};
ListNode<T> *head;
ListNode<T> *tail;
int numNodes;
};
#endif
结构体ListNode
不必是模板,因为它已经是模板类中定义的嵌套类型。
就像这样定义它:
struct ListNode
{
ListNode()
{
next = NULL;
}
ListNode(T value)
{
contents = value;
next = NULL;
}
T contents;
ListNode *next;
};
然后仅使用LinkedList<T>::ListNode
(或仅在类内使用ListNode
)。
例如,成员head
和tail
变成:
ListNode *head;
ListNode *tail;
重要:如果该结构体用于公共函数(例如:void insertNode(ListNode *newNode)
),则不能在private节中定义该结构体。否则,您应该如何创建ListNode
从类外部调用insertNode
?