Dover Organization Interview Question
Developer Program EngineersCountry: India
Interview Type: In-Person
#include <iostream>
using namespace std;
struct Node
{
int mData;
Node* mNext;
Node(int data , Node* next=nullptr):mData(data),mNext(next) {}
};
struct List
{
List():mHead(nullptr){}
Node* mHead;
void Add(int data)
{
if(!mHead)
mHead = new Node(data);
else
{
Node* temp = mHead;
while(temp->mNext != nullptr)
temp = temp->mNext;
temp->mNext = new Node(data);
}
}
void Display()
{
Node *temp = mHead;
cout<<"\n Content of List are : ";
while(temp != nullptr)
{
cout<<"\t"<<temp->mData;
temp = temp->mNext;
}
}
void Find_Last_nth_Element(int count)
{
if( (count>0) && mHead)
{
Node* temp = mHead;
int index = 0;
while( (index < count) && temp )
{
temp = temp->mNext;
++index;
}
if(index != count)
cout<<"\n lesser elements in List"<<endl;
else
{
Node* nthNode = mHead;
while(temp)
{
temp = temp->mNext;
nthNode = nthNode->mNext;
}
cout<<"\n the "<<count<<" node from last in list is "<<nthNode->mData;
}
}
}
};
void main()
{
cout<<"\n Program Started"<<endl;
List myList;
for(int i=0;i<20;++i)
myList.Add(10*i+i);
myList.Display();
int nthNode=0;
cout<<"\nEnter nth Element from last:";
cin>>nthNode;
myList.Find_Last_nth_Element(nthNode);
cout<<"\n Program Ended"<<endl;
}
- Anonymous April 30, 2012