Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 23 additions & 15 deletions LL1/PrintithNode.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,28 @@ public static void printIth(LinkedListNode<Integer> head, int i){
* Print output and don't return it.
* Taking input is handled automatically.
*/
LinkedListNode<Integer> 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<Integer> 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*/
}
}