使用 C++ 刪除連結串列的第一個節點


給定一個連結串列,我們需要刪除其第一個元素並返回新連結串列的頭指標。

Input : 1 -> 2 -> 3 -> 4 -> 5 -> NULL
Output : 2 -> 3 -> 4 -> 5 -> NULL

Input : 2 -> 4 -> 6 -> 8 -> 33 -> 67 -> NULL
Output : 4 -> 6 -> 8 -> 33 -> 67 -> NULL

在給定的問題中,我們需要刪除列表的第一個節點,並將我們的頭移動到第二個元素並返回頭。

尋找解決方案的方法

在這個問題中,我們可以將頭移動到下一個位置,然後釋放上一個節點。

示例

#include <iostream>
using namespace std;
/* Link list node */
struct Node {
   int data;
   struct Node* next;
};
void push(struct Node** head_ref, int new_data) { // pushing the data into the list
   struct Node* new_node = new Node;
   new_node->data = new_data;
   new_node->next = (*head_ref);
   (*head_ref) = new_node;
}
int main() {
   Node* head = NULL;
   push(&head, 12);
   push(&head, 29);
   push(&head, 11);
   push(&head, 23);
   push(&head, 8);
   auto temp = head; // temp becomes head
   head = head -> next; // our head becomes the next element
   delete temp; // we delete temp i.e. the first element
   for (temp = head; temp != NULL; temp = temp->next) // printing the list
      cout << temp->data << " ";
   return 0;
}

輸出

23 11 29 12

上述程式碼的解釋

在這個程式中,我們只需要將頭移動到它的下一個元素,然後刪除上一個元素,然後列印新的列表。給定程式的整體時間複雜度為 O(1),這意味著我們的程式不依賴於給定的輸入,並且它是我們所能達到的最佳複雜度。

結論

在本文中,我們解決了一個刪除連結串列第一個節點的問題。我們還學習了這個問題的 C++ 程式以及我們解決的完整方法。我們可以用其他語言(如 C、Java、Python 等)編寫相同的程式。我們希望您發現本文有所幫助。

更新於: 2021年11月26日

183 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.