我需要输出一个链表中的节点数。我的老师说这个链表跟踪了它的数据并“知道”有多少个节点。所以,我不需要一个while循环来确定链表的大小。我很难弄清楚一个方法,而不是一个while循环来打印出大小。如何确定链接列表的大小而不使用while循环?
这是链表:
template <class T>
class LinkedList
{
private:
struct ListNode
{
T data ;
struct ListNode * next;
};
ListNode *head;
public:
LinkedList() { head = nullptr; }
~LinkedList();
// Linked list operations
void insertNode(T);
bool deleteNode(T);
void displayList() const;
};
/////////// Implementation portion of linked list with template //////////////
// displayList: print all list data
template <class T>
void LinkedList<T>::displayList() const
{
ListNode * ptr = head;
while (ptr != nullptr)
{
cout << ptr->data << endl;
ptr = ptr->next;
}
}
// insertNode: add a node in list order
template <class T>
void LinkedList<T>::insertNode(T newValue)
{
ListNode *newNode;
ListNode *pCur;
ListNode *pPre = NULL;
newNode = new ListNode;
newNode->data = newValue;
newNode->next = nullptr;
if (head == nullptr)
{
head = newNode;
}
else
{
pCur = head;
pPre = nullptr;
while (pCur != nullptr && pCur->data < newValue)
{
pPre = pCur;
pCur = pCur->next;
}
if (pPre == nullptr)
{
head = newNode;
newNode->next = pCur;
}
else
{
pPre->next = newNode;
newNode->next = pCur;
}
}
}
// deleteNode: delete a node if found
template <class T>
bool LinkedList<T>::deleteNode(T toBeDeleted)
{
ListNode *pCur;
ListNode *pPre;
if (!head)
return true;
pCur = head;
pPre = NULL;
while (pCur != NULL && pCur->data < toBeDeleted)
{
pPre = pCur;
pCur = pCur->next;
}
if (pCur != NULL && pCur->data == toBeDeleted)
{
if (pPre)
pPre->next = pCur->next;
else
head = pCur->next;
delete pCur;
return true;
}
return false;
}
// destructor, delete all nodes
template <class T>
LinkedList<T>::~LinkedList()
{
ListNode *ptr = head;
while (ptr != NULL)
{
head = head->next;
delete ptr;
ptr = head;
}
}
这取决于你的链表是如何实现的。如果它跟踪节点的数量,那么你不需要循环。它没有,那么你别无选择,只能遍历所有节点。由于您没有显示实施情况,我们无法提供答案。 –
一种选择是以某种方式在每个节点上存储计数。那么你只需要访问尾部就可以找出有多少个节点。但是这会使诸如添加和删除等操作复杂化。 –
请花些时间阅读[帮助页面](http://stackoverflow.com/help),尤其是名为[“我可以问些什么话题?”](http://stackoverflow.com/help /主题)和[“我应该避免问什么类型的问题?”](http://stackoverflow.com/help/dont-ask)。另请[请阅读如何提出好问题](http://stackoverflow.com/help/how-to-ask),并学习如何创建[最小,完整和可验证示例](http:// stackoverflow .COM /帮助/ MCVE)。 –