From 2e72b2dfae61dbc0040c8ca874ecabf7367eb12b Mon Sep 17 00:00:00 2001 From: Bhavya Kalra <71188028+Bkalra08@users.noreply.github.com> Date: Tue, 13 Oct 2020 20:08:28 +0530 Subject: [PATCH] simplifying the code simplifying the code and easy to understand with description of every step. --- LL1/PrintithNode.java | 38 +++++++++++++++++++++++--------------- 1 file changed, 23 insertions(+), 15 deletions(-) diff --git a/LL1/PrintithNode.java b/LL1/PrintithNode.java index 86b56fd..4c97d86 100644 --- a/LL1/PrintithNode.java +++ b/LL1/PrintithNode.java @@ -19,20 +19,28 @@ public static void printIth(LinkedListNode head, int i){ * Print output and don't return it. * Taking input is handled automatically. */ - LinkedListNode temp = head; - int count = 0; - while (temp != null) { - if (count == i) { - System.out.println(temp.data); - return; - } else { - count++; - temp = temp.next; - if (count == i) { - System.out.println(temp.data); - return; - } - } - } +// LinkedListNode temp = head; +// int count = 0; +// while (temp != null) { +// if (count == i) { +// System.out.println(temp.data); +// return; +// } else { +// count++; +// temp = temp.next; +// if (count == i) { +// System.out.println(temp.data); +// return; +// } +// } +// } + int position = 0; /*initial position is 0 and will be getting updated after each iteration */ + while(temp != null && position < i){ + temp = temp.next; /*the present temp is pointing towards the next one */ + position++; /*position is moved/increased by one*/ + }/*we can use position +=1 also*/ + if(temp = null ){ + System.out.println(temp.data); + } /*the while loop will keep executing till we reach the end element i.e the ith element*/ } }