From e6a8eb4f52d0271ef7ea1d5162ea349089108fee Mon Sep 17 00:00:00 2001 From: pearlgupta2000 <44175292+pearlgupta2000@users.noreply.github.com> Date: Sun, 18 Oct 2020 00:29:29 +0530 Subject: [PATCH] Create Kth Element from last in LL.cpp C++ code for printing kth last element in link list --- Kth Element from last in LL.cpp | 79 +++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 Kth Element from last in LL.cpp diff --git a/Kth Element from last in LL.cpp b/Kth Element from last in LL.cpp new file mode 100644 index 0000000..14d5ae0 --- /dev/null +++ b/Kth Element from last in LL.cpp @@ -0,0 +1,79 @@ +#include +using namespace std; + +class node{ + public: + int data; + node* next; + + node(int d){ //constructor + data=d; + next=NULL; + } +}; + + +void InsertAtTail(node*&head,int d){ + node*p=new node(d); + if(head==NULL){ + head=p; + } + else{ + node*temp=head; + while(temp->next != NULL){ + temp=temp->next; + } + temp->next=p; + } +} + + +void print(node* head){ + while(head!=NULL){ + cout<data<<" "; + head=head->next; + } +} + + +istream& operator >>(istream& is,node*& head){ + int d; + is>>d; + while(d!=-1){ + InsertAtTail(head,d); + is>>d; + } + return is; +} + + +ostream& operator <<(ostream& os,node*head){ + print(head); + return os; +} + + +int k_last(node* head,int k){ + node*fast=head,*slow=head; + for(int i=1;i<=k;i++) + fast=fast->next; + while(fast!=NULL){ + slow=slow->next; + fast=fast->next; + } + return slow->data; +} + + +int main(){ + node* head=NULL; + + // taking input for link list + cin>>head; + int k; cin>>k; + + int p=k_last(head,k); + //printing kth last element + cout<