Home  >  Article  >  Backend Development  >  Delete the last node of a linked list using C++

Delete the last node of a linked list using C++

王林
王林forward
2023-08-30 19:09:031220browse

Delete the last node of a linked list using C++

We have a singly linked list and our task is to delete the last node from the linked list. In this problem, we just need to traverse the given linked list and simply delete the last node.

Method to find the solution

In this method we traverse the given linked list and keep track of the previous node and the current node. When our current node becomes the last node, we change previous -> next to NULL and delete the current node.

Example

#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;
}

Output

8 23 11 29

Explanation of the above code

In this method, we iterate through the array, keeping track of the current node and the previous node. When the current node becomes the last node, we change previous -> next to NULL and delete the current node. The overall time complexity of the given program is O(N), where N is the size of the given list.

Time Complexity - O(N)

N: size of the given array

Conclusion

In this article, We solved the problem of removing the last node from a given linked list. We also learned the C program for this problem and our complete approach to solving it. We can write the same program in other languages ​​like C, Java, Python and other languages. Hope you find this article helpful.

The above is the detailed content of Delete the last node of a linked list using C++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete