Remove Last Node of the Linked List using C++

C++Server Side ProgrammingProgramming

We are provided with a singly linked list, and we are tasked to remove the last node from that list. In this problem, we are simply going to traverse through the given list and simply remove the last node.

Approach to find The Solution

In this approach, we go through the given list, and we keep track of the previous node and the current node. Now 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 approach, we traverse through the array, keeping track of the current node and the previous node. Now when our 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 our given list.

Time Complexity − O(N)

N: The size of our array

Conclusion

In this article, we solve a problem to Remove the last node from the given linked list. We also learned the C++ program for this problem and the complete approach we solved. We can write the same program in other languages such as C, java, python, and other languages. We hope you find this article helpful.

raja
Updated on 29-Nov-2021 09:36:35

Advertisements