forked from super30admin/PreCourse-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExercise_3.js
41 lines (30 loc) · 1.01 KB
/
Exercise_3.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
//Time Complexity is O(n) since it has to traverse the entire list before adding the new node at the end.
class Node {
constructor(data){
this.data = data
this.nextElement = null
}
}
class LinkedList {
constructor() {
this.head = null
}
push(data) {
let incomingNode = new Node(data)
let existingNode = this.head
if(existingNode === null) {
incomingNode.nextElement = existingNode
return this.head = incomingNode
}
while(existingNode && existingNode.nextElement !== null){
existingNode = existingNode.nextElement;
}
existingNode.nextElement = incomingNode;
return 'Added incoming node ' + JSON.stringify(this.head)
}
}
const myLinkedList = new LinkedList()
//Pushing data at the end of the list. Prints the entire list everytime there is a new push
console.log(myLinkedList.push(1))
console.log(myLinkedList.push(2))
console.log(myLinkedList.push(3))