我需要輸出一個鏈表中的節點數。我的老師說這個鏈表跟蹤了它的數據並「知道」有多少個節點。所以,我不需要一個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)。 –