DigestCPP

Lets Understand With Example

  • Home
  • Design Principal
  • Design Patterns
  • C++ 11 Features
  • C++11 Multithreading
  • Contact Us

Find the last nth Node in Linked list

Find the last 3rd Node from Linked list C++

This question is very frequently asked in interview so please check the below code to find the last nth element from Linked List.

Source code:

/*
Program: Find the last nth element from Linked List 
Author: Alpha Master
Date: 18 Dec 2021
*/

//Header File
#include<iostream>

struct Node
{
	int data;
	Node* next;
};

class Linked
{
	Node* mPtr;
	public:
	Linked(){mPtr = nullptr;}
	~Linked()
	{
		Node* tmp = mPtr;
		while(tmp != nullptr)
		{
			mPtr = tmp->next;
			delete tmp;
			tmp = mPtr;
		}
	}
	void insert(int val);
	void display();
	Node* findLast(int loc);
};

void Linked::insert(int val)
{
	if(mPtr == nullptr)
	{
		mPtr = new Node;
		mPtr->data = val;
		mPtr->next = nullptr;
	}
	//else traverse to last element and add at the end
	else
	{
		Node* tmp = mPtr;
		while(tmp->next != nullptr)
		{
			tmp = tmp->next;	
		}
		tmp->next = new Node;	
		tmp->next->data = val;
		tmp->next->next = nullptr;
	}
	return;
}

void Linked::display()
{
	Node* tmp = mPtr;
	while(tmp != nullptr)
	{
		std::cout<<"Value:"<<tmp->data<<std::endl;
		tmp = tmp->next;
	}
	return;
}

Node* Linked::findLast(int loc)
{
	Node* tmp = mPtr;
	Node* second = nullptr;
	int count = 0;
	//Iterate to last node so check for tmp->next
	while(tmp->next != nullptr)
	{
		//increment the count and first traverse pointer		
		count++;  
		tmp = tmp->next;

		//check the location and start the pointer
		if(count == loc)
		{
			//Pointing to head
			second = mPtr;
		}
		

		if(second != nullptr)
		{
			second = second->next;
		}
	}
	
	std::cout<<"Data:"<<second->data<<std::endl;	
	return second;
}

int main()
{
	std::cout<<"Find the last nth element from Linked List"<<std::endl;
	Linked obj;
	obj.insert(12);
	obj.insert(14);
	obj.insert(4);
	obj.insert(6);
	obj.insert(8);
	obj.insert(2);
	obj.insert(1);
	obj.insert(13);
	obj.insert(55);
	obj.display();
	std::cout<<(obj.findLast(3))->data<<std::endl;
	return 0;
}

Output:

Find the last nth element from Linked List
Value:12
Value:14
Value:4
Value:6
Value:8
Value:2
Value:1
Value:13
Value:55
Data:1
1

Primary Sidebar




DigestCPP © 2023. All rights reserved.

    About Privacy Policy Terms and Conditions Contact Us Disclaimer