From b474538cb8671772b597f66f06e5788669d8d084 Mon Sep 17 00:00:00 2001 From: pawarp19 <112321728+pawarp19@users.noreply.github.com> Date: Wed, 27 Sep 2023 23:07:18 +0530 Subject: [PATCH] Nthnodefromend.cpp --- 1.linked list/Nthnodefromend.cpp | 73 ++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 1.linked list/Nthnodefromend.cpp 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<