Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nthnodefromend.cpp #1747

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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;
}