#include <iostream>
using namespace std;
struct list
{
int data;
struct list *next;
};
typedef struct list node;
node *head=NULL;
void insert_node()
{
node *temp=new node();
node *last;
cout<<"Data: ";
cin>>temp->data;
temp->next=NULL;
if(head==NULL)
{
head=temp;
}
else
{
last = head;
while(last->next != NULL)
{
last = last->next;
}
last->next = temp;
}
}
void print_node()
{
node *temp=head;
if(temp==NULL)
{
cout<<"
No data Found"<<endl;
return;
}
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp = temp->next;
}
}
void find_node(int n)
{
int count=0,i=0;
node *temp=head;
while(temp != NULL) ///count the length
{
count++;
temp = temp->next;
}
count = count - n; ///make count as the nth position from the end
temp = head;
while(i != count) ///find the nth position
{
temp = temp->next;
i++;
}
cout<<"
Data: "<<temp->data<<endl;
}
int main()
{
int flag,n;
do
{
cout<<"Press 1 To insert Node: ";
cin>>flag;
if(flag!=1)break;
insert_node();
}
while(flag==1);
cout<<"
Your Linked List: ";
print_node();
cout<<endl;
cout<<"
Enter The Index From Last: ";
cin>>n;
find_node(n);
return 0;
}
Output
Press 1 To insert Node: 1
Data: 1
Press 1 To insert Node: 1
Data: 2
Press 1 To insert Node: 1
Data: 3
Press 1 To insert Node: 1
Data: 4
Press 1 To insert Node: 1
Data:
5
Press 1 To insert Node: 0
Your Linked List: 1 2 3 4 5
Enter The Index From Last: 2
Data: 4
Add your comment