diff --git a/1.linked list/Nthnodefromend.cpp b/1.linked list/Nthnodefromend.cpp new file mode 100644 index 000000000..cf100444b --- /dev/null +++ b/1.linked list/Nthnodefromend.cpp @@ -0,0 +1,73 @@ + +#include +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;inext; + } + 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>l; + tail->next = new Node(l); + tail = tail->next; + } + Solution obj; + cout<