w3resource

C++ Linked List Exercises: Delete the nth node of a Singly Linked List from end

C++ Linked List: Exercise-13 with Solution

Write a C++ program to delete the nth node of a Singly Linked List from the end.

Test Data:
Original list:
7 5 3 1
Remove the 2nd node from the end of the said list:
Updated list:
7 5 1
Remove the 3rd node from the end of the said list:
Updated list:
5 1

Sample Solution:

C++ Code:

#include <iostream>

using namespace std;

struct  Node
{   
    int num;
    Node *next;
 }; //node constructed

  int size = 0;
  void insert(Node** head, int num){
    Node* new_Node = new Node();
    new_Node->num = num;
    new_Node->next = *head;
    *head = new_Node;    
     size++;
}

Node* delete_last_node(Node* head, int n) {
        Node *p = head, *q = head;
        while (n--) q = q->next;
        if (!q) return head->next;
        while (q->next) {
            p = p->next;
            q = q->next;
        }
        Node* toDelete = p->next;
        p->next = p->next->next;
        delete toDelete;
        return head;
}

  //Display all nodes
  void display_all_nodes(Node* node)
    { 
      while(node!=NULL){
        cout << node->num << " "; 
        node = node->next; 
    } 
}

int main()
{
    Node* head = NULL;
    insert(&head,1);
    insert(&head,3);
    insert(&head,5);
    insert(&head,7);
    cout << "Original list:\n";
    display_all_nodes(head); 
    int pos = 2;
    cout << "\n\nRemove the " << pos << "nd node from the end of the said list:";
    cout << "\nUpdated list:\n";
    head = delete_last_node(head, pos);
    display_all_nodes(head); 
    pos = 3;
    cout << "\n\nRemove the " << pos << "rd node from the end of the said list:";
    cout << "\nUpdated list:\n";
    head = delete_last_node(head, pos);
    display_all_nodes(head); 
    cout<<endl;
    return 0;
}

Sample Output:

Original list:
7 5 3 1

Remove the 2nd node from the end of the said list:
Updated list:
7 5 1

Remove the 3rd node from the end of the said list:
Updated list:
5 1

Flowchart:

Flowchart: Delete the nth node of a Singly Linked List from end.
Flowchart: Delete the nth node of a Singly Linked List from end.

CPP Code Editor:

Contribute your code and comments through Disqus.

Previous C++ Exercise: Delete the last node of a Singly Linked List.
Next C++ Exercise: Kth node from the Middle towards Head of a Linked List.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.

C++ Programming: Tips of the Day

Why is there no std::stou?

The most pat answer would be that the C library has no corresponding "strtou", and the C++11 string functions are all just thinly veiled wrappers around the C library functions: The std::sto* functions mirror strto*, and the std::to_string functions use sprintf.

Ref: https://bit.ly/3wtz2qA

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook