ani03sha / Algorithms

This repository contains implementations of common data structures and algorithms
Apache License 2.0
2 stars 1 forks source link

Linkedlist finding last node code seems broken #33

Closed vaibhav26sharma closed 3 years ago

vaibhav26sharma commented 3 years ago

@ani03sha I see a bug in line: https://github.com/ani03sha/Algorithms/blob/fc37c3f41c05d18fc8043aecad308c8f40cee635/src/main/java/org/redquark/algorithms/datastructures/lists/LinkedList.java#L164

Correct code- temp.next!=null

Do let me know in case I am missing out on anything here.

vaibhav26sharma commented 3 years ago

@ani03sha Looking at the code after loop I think you are trying to find the last 2nd node itself, however the code comment is misleading.

ani03sha commented 3 years ago

@vaibhav6451956, the while loop will run until temp.next.next != null which means, the condition will be true for the 3rd-last node for all n >= 3, n being the length of the list. Since this condition is true, the flow will go inside the loop and then move temp to the second last node and the loop will break. Now, outside the loop, we will get the data stored in the last node using temp.next.data (temp.next pointing to the last node). Then we will make next of temp (currently the second last node) as null to end the list. LMK in case we further need to look into this.

Thanks for taking the time to review this stuff :smiley:

vaibhav26sharma commented 3 years ago

@ani03sha Thanks for explaining!

I was able to make sense of that part of code when I read it further, although the line comment can be updated since it is a bit misleading.