使用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和其他語言編寫相同的程式。希望本文對您有所幫助。

更新於:2021年11月29日

157 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告