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

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

王林
王林轉載
2023-08-30 19:09:031162瀏覽

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

我們有一個單鍊錶,並且我們的任務是從該鍊錶中刪除最後一個節點。在這個問題中,我們只需要遍歷給定的鍊錶,並且簡單地刪除最後一個節點。

找到解決方案的方法

在這種方法中,我們遍歷給定的鍊錶,並追蹤前一個節點和當前節點。當我們的目前節點成為最後一個節點時,我們將previous -> next改為NULL,並刪除目前節點。

範例

#include <iostream>
using namespace std;

struct Node {
   int data;
   struct Node* next;
};
void push(struct Node** ref, int new_data) { // pushing the node
   struct Node* new_n = new Node;
   new_n->data = new_data;
   new_n->next = (*ref);
   (*ref) = new_n;
}
int main() {
   Node* head = NULL;
   push(&head, 12);
   push(&head, 29);
   push(&head, 11);
   push(&head, 23);
   push(&head, 8);
   auto curr = head, prev = head;
   if (!curr || !curr -> next) // if list only has one element or the list is empty
      cout << "Empty\n";
   else {
      while (curr) { // while curr != NULL
         if (!curr -> next) {
            prev -> next = NULL;
            delete(curr); // freeing the space
            break;
         }
         prev = curr;
         curr = curr -> next; // moving to the next node
      }
   }
   for (Node* temp = head; temp != NULL; temp = temp->next) // printing the data
      cout << temp->data << " ";

   return 0;
}

輸出

8 23 11 29

上述程式碼的解釋

在這個方法中,我們遍歷數組,追蹤目前節點和上一個節點。當目前節點成為最後一個節點時,我們將previous -> next改為NULL並刪除目前節點。給定程式的總體時間複雜度為O(N),其中N是給定列表的大小。

時間複雜度- O(N)

N:給定陣列的大小

結論

在本文中,我們解決了從給定鍊錶中刪除最後一個節點的問題。我們也學習了這個問題的C 程式和我們解決的完整方法。我們可以用其他語言寫相同的程序,如C、Java、Python和其他語言。希望您會發現本文有幫助。

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

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