Write a function to get Nth node in Linked List.The prototype of the getNth_node() is as follows:
void getNth_node(int N)
{
};
This function will take N as an argument and display the content of the node at index N (1<=N<=len) ,where len is the length of the Linked List.
Solution:
/*
Problem Description
write a function to get Nth node in a linked list\
submitted by
Arjun Mishra
*/
#include<iostream>
#include<stdlib.h>
using namespace std;
struct node
{
int data;
struct node* next;
}*head,*tail,*temp;
int count=0,len=0;
void push(int val)
{
temp=(struct node*)malloc(sizeof(struct node));
if(!(temp))
{
cout<<"Problem in creating Node!\n";
return;
}
::len++;
temp->data=val;
temp->next=NULL;
if(head==NULL)
{
head=temp;
tail=temp;
}
else
{
tail->next=temp;
tail=temp;
}
}
void traverse()
{
if(head==NULL)
cout<<"List is Empty\n";
else
{
temp=head;
while(temp!=NULL)
{
cout<<temp->data<<"->";
temp=temp->next;
}
cout<<"NULL"<<endl;
}
}
void getNth_node(int N)
{
temp=head;
while(temp!=NULL)
{
::count++;
if(::count==N)
{
cout<<"The value at node is:"<<temp->data<<endl;
break;
}
temp=temp->next;
}
}
int main()
{
int N;
push(23);
push(4);
push(7);
push(8);
push(10);
push(18);
cout<<"The list is as follows\n";
traverse();
cout<<"Enter the value of N\n";
cin>>N;
if((::len)<(N))
cout<<"No such node exists\n";
else
getNth_node(N);
return 0;
}
void getNth_node(int N)
{
};
This function will take N as an argument and display the content of the node at index N (1<=N<=len) ,where len is the length of the Linked List.
Solution:
/*
Problem Description
write a function to get Nth node in a linked list\
submitted by
Arjun Mishra
*/
#include<iostream>
#include<stdlib.h>
using namespace std;
struct node
{
int data;
struct node* next;
}*head,*tail,*temp;
int count=0,len=0;
void push(int val)
{
temp=(struct node*)malloc(sizeof(struct node));
if(!(temp))
{
cout<<"Problem in creating Node!\n";
return;
}
::len++;
temp->data=val;
temp->next=NULL;
if(head==NULL)
{
head=temp;
tail=temp;
}
else
{
tail->next=temp;
tail=temp;
}
}
void traverse()
{
if(head==NULL)
cout<<"List is Empty\n";
else
{
temp=head;
while(temp!=NULL)
{
cout<<temp->data<<"->";
temp=temp->next;
}
cout<<"NULL"<<endl;
}
}
void getNth_node(int N)
{
temp=head;
while(temp!=NULL)
{
::count++;
if(::count==N)
{
cout<<"The value at node is:"<<temp->data<<endl;
break;
}
temp=temp->next;
}
}
int main()
{
int N;
push(23);
push(4);
push(7);
push(8);
push(10);
push(18);
cout<<"The list is as follows\n";
traverse();
cout<<"Enter the value of N\n";
cin>>N;
if((::len)<(N))
cout<<"No such node exists\n";
else
getNth_node(N);
return 0;
}
No comments:
Post a Comment