From bad1657535e139c63b19cf19986aa14d1db5359a Mon Sep 17 00:00:00 2001 From: Shashwat jaiswal Date: Fri, 17 Jun 2022 12:55:15 +0530 Subject: [PATCH] Kth Last element in a single pass The existing solution runs two loops to achieve the result. This proposed solution works by using a single while loop. --- .../Linked List/KthLastElement.cpp | 29 +++++++++---------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/DSA Essentials Solutions/Linked List/KthLastElement.cpp b/DSA Essentials Solutions/Linked List/KthLastElement.cpp index c1189c0..e1ba30d 100644 --- a/DSA Essentials Solutions/Linked List/KthLastElement.cpp +++ b/DSA Essentials Solutions/Linked List/KthLastElement.cpp @@ -17,19 +17,18 @@ class node{ int kthLastElement(node * head,int k){ //Complete this function to return kth last element - node * fast = head; - node * slow = head; + int count{1}; + node *i = head; + node *j = head; - int cnt = 0; - while(cnt < k){ - fast = fast->next; - cnt++; - } - - while(fast!=NULL){ - slow = slow->next; - fast = fast->next; - } - - return slow->data; -} \ No newline at end of file + while (j->next!=NULL){ + if(count>=k){ + i = i->next; + } + j = j->next; + count++; +} + + return i->data; + +}