我想在C++的鏈表中添加一個節點。我已經開發了添加到列表末尾的代碼,這比我的大腦更容易理解。這裏是我的代碼:
類
如何將節點添加到鏈接列表C++的前面?我正在超越這個概念
struct ListNode
{
double value;
ListNode *next;
ListNode(double value1, ListNode *next1 = NULL)
{
value = value1;
next = next1;
}
};
ListNode *head; // List head pointer
的功能添加到列表的末尾
void LinkedList::add(double number)
{
if (head == NULL)
head = new ListNode(number);
else
{
// The list is not empty
// Use nodePtr to traverse the list
ListNode *nodePtr = head;
while (nodePtr->next != NULL)
nodePtr = nodePtr->next;
// nodePtr->next is NULL so nodePtr points to the last node
// Create a new node and put it after the last node
nodePtr->next = new ListNode(number);
}
}
我只是有很多的麻煩包裝我的頭移動所有的指針添加到開始。
謝謝。
繪製節點和鏈接和指針通常有助於集中精神。 –
將新節點添加到鏈表的前端比將其添加到列表的末尾要容易得多,特別是在沒有「尾部」指針的單鏈表中。 –