I'm reading Cracking the Coding Interview and doing practice problems and I'm stuck on this one:
"Implement an algorithm to find the kth to last element of a singly linked list."
My recursive function is not returning anything and I am not able to figure out why. In the recursive function I am taking 3 parameters. K
will be the position from the last element that we want to find out. Node* temp
will be the head node and int i will keep a count of elements from the last node.
#include<bits/stdc++.h>
using namespace std;
class Node
{
int data;
Node* next;
public:
Node(){
data=0;
next=NULL;
}
friend class LinkedList;
};
class LinkedList
{
public:
Node* head;
public:
LinkedList(){
head=NULL;
}
void append(int data){
Node* temp= new Node();
temp->data=data;
temp->next=NULL;
if (head==NULL){
head=temp;
}
else{
Node* ptr=head;
while(ptr->next!=NULL){
ptr=ptr->next;
}
ptr->next=temp;
}
}
void display(){
Node* ptr=head;
if(head==NULL){
cout<<"List is empty"<<endl;
return;
}
while(ptr!=NULL){
cout<<ptr->data<<"->";
ptr=ptr->next;
}
cout<<"NULL";
}
//using recursive solution
int kth_to_last2(int k,Node* temp,int &i){
if(temp==NULL){
return 0;
}
int index=kth_to_last2(k,temp->next,i);
i++;
if(i==k){
return temp->data;
}
cout<<endl;
return index;
}
};