javascript-algorithms
javascript-algorithms copied to clipboard
Code misbehavior(mild) : LinkedList.append(), according to code, should add to tail, but actually append to head
How to recreate the problem
- Copy the LinkedList.js, LinkedListNode.js, Comparator.js code to the console of Chrome DevTool
- Add
console.logto theappend()method.
- Add
- 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
- Line 51 and Line 52
- Code
- Comparator Code
@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

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