Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions 1.linked list/Nthnodefromend.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@

#include <bits/stdc++.h>
using namespace std;

/* Link list Node */
struct Node {
int data;
struct Node *next;
Node(int x) {
data = x;
next = NULL;
}
};
int getNthFromLast(struct Node* head, int n);

/* struct Node {
int data;
struct Node *next;
Node(int x) {
data = x;
next = NULL;
}
};
*/

//Function to find the data of nth node from the end of a linked list.
class Solution{
public:
int getNthFromLast(Node *head, int n)
{
Node *slow=head;
Node *fast=head;
for(int i=0;i<n;i++)
{
if(fast==NULL)
return -1;
fast=fast->next;
}
while(fast!=NULL)
{
slow=slow->next;
fast=fast->next;
}
return slow->data;
}
};


int main()
{
int T,i,n,l,k;

cin>>T;

while(T--){
struct Node *head = NULL, *tail = NULL;

cin>>n>>k;
int firstdata;
cin>>firstdata;
head = new Node(firstdata);
tail = head;
for(i=1;i<n;i++)
{
cin>>l;
tail->next = new Node(l);
tail = tail->next;
}
Solution obj;
cout<<obj.getNthFromLast(head, k)<<endl;
}
return 0;
}