trekhleb / javascript-algorithms

📝 Algorithms and data structures implemented in JavaScript with explanations and links to further readings
MIT License
187.92k stars 30.2k forks source link

Code misbehavior(mild) : LinkedList.append(), according to code, should add to tail, but actually append to head #544

Open zhutoutoutousan opened 4 years ago

zhutoutoutousan commented 4 years ago

How to recreate the problem

  1. Copy the LinkedList.js, LinkedListNode.js, Comparator.js code to the console of Chrome DevTool
    • Add console.log to the append() method.
  2. Add test code

let a = new LinkedList(); a.append(5) a.append(7) // In the append method, it was this.tail = newNode, but in chrome console, // it can be observed that it was added to head.

// If I changed the this.tail = newNode to this.head = newNode, it appended to the tail

// If I add some console.log in the append method, // it could be observed that the class instance is already been changed // before the console.log was reached(applies even when console.log is at the start of the method.



# Intention
- As a beginner, I just want to know why it happened, as far as I know about 'If it is not broke, don't fix it.', I am still interested in what actually happened in JavaScript.
- My instinct told me it maybe has something to do with mutability, but I am not sure what exactly it is. 
# Source
- [Code](https://github.com/trekhleb/javascript-algorithms/blob/master/src/data-structures/linked-list/LinkedList.js)
    - Line 51 and Line 52
- [Code](https://github.com/trekhleb/javascript-algorithms/blob/master/src/data-structures/linked-list/LinkedListNode.js)
- [Comparator Code](https://github.com/trekhleb/javascript-algorithms/blob/07bc4a4b975d7069a69421e7e6ad256ba76b721c/src/utils/comparator/Comparator.js#L1)
gkhedekar5758 commented 2 years ago

@zhutoutoutousan sir apologies but i see it correct. once the line a.append(5) gets executed there is nothing in the linkedList so the '5' becomes the head value and then the 7 will be appended so added to the next node's value.

see below image, the head has value of 5

image

just wanted to understand your view point, may be there is some bug that I am not observing. let me know. I would be very much interested in this