In this shot, we'll solve a commonly asked interview question on linked list. The problem statement is as follows:
You are given the head of a linked list and an integer
Let's first understand the problem statement. Suppose that you have the following linked list:
Also, you are given the value of
Now that the problem statement is clear, let's try to think about the solution.
We'll follow the steps mentioned below to build up an algorithm to solve the problem.
num_nodes
.position_start
=
num_nodes - n + 1
.
#include<iostream>using namespace std;// Structure of a linked list nodestruct ListNode {int val;ListNode *next;};// head pointerListNode *head = NULL;// Function to create a linked listListNode* createLinkedList(){ListNode *temp;for(int i = 5; i >= 1; i--){ListNode* node = new ListNode();node->val = i;node->next = NULL;if(head == NULL){head = node;temp = node;}else{temp->next = node;temp = node;}}return head;}// Function to display the nodes present in the linked listvoid displayLinkedList(ListNode* head){struct ListNode *current = head;if(head == NULL) {cout << "List is empty";return;}cout << "Nodes of singly linked list: \n";while(current != NULL) {cout << current->val << " ";current = current->next;}}// Count the total number of nodes present in the linked listint countNodes(ListNode* head){ListNode* temp = head;int numNodes = 0;while(temp != NULL){numNodes++;temp = temp -> next;}return numNodes;}// Remove the Nth node from the end of the linked listListNode* removeNthFromEnd(ListNode* head, int n) {int numNodes = countNodes(head);int removePos = numNodes - n + 1;if (numNodes == 1 && removePos == 1)return NULL;ListNode *temp = head, *prev = NULL;numNodes = 0;while(temp != NULL){numNodes++;if (numNodes == removePos){if (prev == NULL)head = temp -> next;elseprev->next = temp->next == NULL ? NULL: temp->next;break;}prev = temp;temp = temp->next;}return head;}// Main functionint main(){// Create a linked list and print itListNode* head = createLinkedList();displayLinkedList(head);// Delete the Nth node and print the linked listcout << endl;head = removeNthFromEnd(head, 2);displayLinkedList(head);return 0;}
createLinkedList()
to create a linked list of 5 nodes.displayLinkedList()
to display the nodes present in the linked list.countNodes()
to count the total number of nodes that are present in the linked list.removeNthFromEnd()
that will accept the head
of the linked list and the position of the node n
that needs to be deleted from the end. NULL
if there is a single node present in the linked list.while
loop to iterate over all the nodes until we come to the position at which the node needs to be deleted.head
of the linked list.Note: If you want to learn and solve more coding interview questions, you can check out the course Competitive Programming - Crack Your Coding Interview, C++.