使用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 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.