-
Notifications
You must be signed in to change notification settings - Fork 0
/
singly_linked_list.js
83 lines (78 loc) · 1.88 KB
/
singly_linked_list.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
/*
What is a linked list - a Data structure tha contains a head, tail and length property
- consists of nodes and each node has a value and a pointer to another node or null
- There is no index
- Connected via nodes with a next pointer
- Random access is not allowed
- Piece of data - Val
- Reference to next node - Next
*/
class Node{
constructor(val) {
this.val = val
this.next = null
}
}
class SinglyLinkedList{
constructor(){
this.head = null
this.tail = null
this.length = 0
}
//pushing
push(val) {
var newNode = new Node(val)
if(!this.head){
this.head = newNode
this.tail = this.head
} else {
this.tail.next = newNode
this.tail = newNode
}
this.length++
return this
}
pop() {
if(!this.head) return undefined
var current = this.head
var newTail = current
while(current.next) {
newTail = current
current = current.next
}
this.tail = newTail
this.tail.next = null
this.length--
if(this.length === 0) {
this.head = null
this.tail = null
}
return current
}
shift(){
if(!this.head) return undefined
var currentHead = this.head
this.head = currentHead.next
this.length--
if(this.length === 0) {
this.tail = null
}
return currentHead
}
unshift(val) {
var newNode = new Node(val)
if(!this.head) {
this.head = newNode
this.tail = this.head
} else {
newNode.next = this.head
this.head = newNode
}
this.length++
return this
}
}
var list = new SinglyLinkedList()
console.log(list.push("Hello"))
list.push("Goodbye")
list.push("!")