例如,有一個鍛鍊,上面寫着:只給出該指針是否可以刪除鏈表中的最後一個節點?
寫一個函數刪除鏈表中的節點,這是解決方案:
void deleteNode(Node* toDelete) { // this function essensially first copies the data from the next pointer // and then, deletes the next pointer // However, it doesn't work if trying to delete the last element in the list Node *temp = toDelete->next; // create a temp, assign to the one after toDelete toDelete->data = temp->data; // change toDelete's data to the one's after it toDelete->next = temp->next; // change toDelete's next to the one's after it delete temp; temp = nullptr; }
如何更改我的解決方案,以便能夠刪除鏈接列表中的最後元素,給定只有指針最後一個節點?
最後一個節點與其他節點有什麼不同?您如何測試? – juanchopanza
它沒有指向什麼?接下來是nullptr – Oleksiy
所以,也許你可以使用這些信息爲該節點做一些不同的事情。 – juanchopanza