#include
using namespace std;
class node{
public:
int data;
nodenext;
node(int d)
{
data=d;
next=NULL;
}
};
int length(nodehead)
{
int len=0;
while(head!=NULL)
{
head=head->next;
len+=1;
}
return len;
}
nodelastelement(nodehead,int pos)
{
if(head==NULL || head->next==NULL)
{
return head;
}
nodeslow=head;
nodefast=head;
int jump=1;
while(jump<=length(head)-pos)
{
fast=fast->next;
jump++;
}
while(fast!=NULL)
{
fast=fast->next;
slow=slow->next;
}
return slow;
}
void insertattail(node*&head,int data)
{
if(head==NULL)
{
head=new node(data);
return;
}
nodetail=head;
while(tail->next!=NULL)
{
tail=tail->next;
}
tail->next=new node(data);
return;
}
void buildlist(node&head)
{
int data;
cin>>data;
while(data!=-1)
{
insertattail(head,data);
cin>>data;
}
}
int main() {
nodehead=NULL;
buildlist(head);
int pos;
cin>>pos;
nodem=lastelement(head,pos);
cout<data;
return 0;
}
What is wrong with the code. plz tell and also correct it
but it is failing two test cases and one run time error.
@Kunalgoyal
i have corrected the function, please see
Mark the doubt as resolved in case of no further queries.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.