首頁  >  文章  >  後端開發  >  使用C++刪除鍊錶的第一個節點

使用C++刪除鍊錶的第一個節點

WBOY
WBOY轉載
2023-09-22 09:17:081415瀏覽

使用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等語言來寫同樣的程式。我們希望這篇文章對您有幫助。

以上是使用C++刪除鍊錶的第一個節點的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除