javascript-algorithms icon indicating copy to clipboard operation
javascript-algorithms copied to clipboard

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

Open zhutoutoutousan opened this issue 5 years ago • 1 comments

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

zhutoutoutousan avatar Sep 22 '20 08:09 zhutoutoutousan

@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

gkhedekar5758 avatar Jun 21 '22 05:06 gkhedekar5758