@violangreg/

building a LinkedList

Nodejs

No description

fork
loading
Files
  • index.js
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
class Node {
  constructor(v){
    this.value = v;
    this.next = null;
  }
}

class MyLinkedList {
  constructor(v){
    this.head = new Node(v);
    this.tail = this.head;
    if(v === undefined)
      this.length = 0;
    else
      this.length = 1;
  }

  prepend(v){
    if(this.head.value === undefined){
      this.head.value = v;
      this.length++;
    }
    else{
      const node = new Node(v);
      node.next = this.head;
      this.head = node;
      this.length++;
    }
    return this;
  }

  append(v){
    if(this.tail.value === undefined){
      this.tail.value = v;
      this.length++;
    }
    else{
      const node = new Node(v);
      this.tail.next = node;
      this.tail = node;
      this.length++;
    }
    return this;
  }

  printList(){
    const array = [];
    let currentNode = this.head;
    while(currentNode !== null){
      array.push(currentNode.value);
      currentNode = currentNode.next;
    }
    return array;
  }

  insert(i, v){
    if(i > this.length || i < 0)
      return;
    else if(i === 0)
      return this.prepend(v);
    else if(i >= this.length)
      return this.append(v);
    
    const node = new Node(v);
    const prevNode = this.traverseToIndex(i-1);
    const currentNode = prevNode.next; // since prevNode is already assigned the line before, the currentNode is the next of it
    node.next = currentNode;
    prevNode.next = node;
  }

  remove(i){
    if(i > this.length || i < 0)
      return;
    else if(i === 0)
      return this.head = this.head.next;

    const prevNode = this.traverseToIndex(i-1);
    const unwantedNode = prevNode.next;
    prevNode.next = unwantedNode.next;
    this.length--;
  }

  get(i){
    return this.traverseToIndex(i).value;
  }

  traverseToIndex(i){
    if(i > this.length || i < 0)
      return;
    let currentNode = this.head;
    for(let k = 0; k < i; k++)
      currentNode = currentNode.next;
    return currentNode;
  }
}

const myLL = new MyLinkedList();
myLL.append(2);
myLL.append(3);
myLL.append(4);
myLL.insert(2, 7);
console.log(myLL.get(2));
myLL.printList();



node v10.16.0