首页 > 文章列表 > 使用C++删除链表的最后一个节点

使用C++删除链表的最后一个节点

C链表删除最后节点
106 2023-08-30

我们有一个单链表,并且我们的任务是从该链表中删除最后一个节点。在这个问题中,我们只需要遍历给定的链表,并简单地删除最后一个节点。

找到解决方案的方法

在这种方法中,我们遍历给定的链表,并跟踪前一个节点和当前节点。当我们的当前节点成为最后一个节点时,我们将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 << "Emptyn";
   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和其他语言。希望您会发现本文有帮助。