forked from super30admin/PreCourse-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExercise_3.js
52 lines (42 loc) · 1.12 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
42
43
44
45
46
47
48
49
50
51
52
class Node {
constructor(data){
this.data = data
this.nextElement = null
}
}
class LinkedList {
constructor() {
this.head = null
}
isEmpty() {
return this.head === null
}
push(data) {
let incomingNode = new Node(data)
let existingNode = this.head
incomingNode.nextElement = existingNode
this.head = incomingNode
return 'Added incoming node ' + JSON.stringify(this.head)
}
printMiddle() {
if (this.isEmpty()) {
return "Please add node elements to the list"
} else {
let slow = this.head
let fast = this.head
while(fast && fast.nextElement) {
slow = slow.nextElement
fast = fast.nextElement.nextElement
}
return slow
}
}
}
const myLinkedList = new LinkedList()
//Pushing nodes
console.log(myLinkedList.push(1))
console.log(myLinkedList.push(2))
console.log(myLinkedList.push(3))
console.log(myLinkedList.push(4))
// Print middle of the list
console.log(myLinkedList.printMiddle())