Repository navigation
Expand file tree
/
Copy pathsllNextWeek.js
More file actions
133 lines (120 loc) · 2.27 KB
/
Copy pathsllNextWeek.js
File metadata and controls
133 lines (120 loc) · 2.27 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
class Node {
constructor(element) {
this.element = element
this.next = null
}
}
class SinglyLinkedList {
constructor() {
this.head = null
this.size = 0
}
addToHead(element) {
const node = new Node(element)
var cur = this.head
var prev = cur
this.head = node
node.next = prev
this.size++
}
addToEnd(element) {
const node = new Node(element)
var cur = this.head
if (this.head === null) {
this.head = node
} else {
while (cur) {
cur = cur.next
}
cur = node
}
this.size++
}
deleteFrom(location) {
var cur = this.head
// console.log('cur', cur)
var prev = cur
var SLLLocation = 0
// console.log('next', cur)
if (location === 0) {
this.head = cur.next
} else {
while (location != SLLLocation) {
prev = cur
cur = cur.next
SLLLocation++
}
prev.next = cur.next
return cur.element
}
this.size--
}
reverseList() {
var list = []
var cur = this.head
while (cur) {
list.push(cur.element)
this.deleteFrom(0)
cur = cur.next
}
const reverseList = list.reverse()
for (var i = 0; i < reverseList.length; i++) {
const listElement = reverseList[i]
this.addToEnd(listElement)
}
}
findBy(location) {
var listLocation = 0
var cur = this.head
while (location != listLocation) {
listLocation++
cur = cur.next
}
console.log(cur.element)
}
isInList(value) {
var cur = this.head
var inList = false
while (cur.next) {
if ((cur.element = value)) {
inList = true
}
}
console.log(inList)
}
// helper methods
isListEmpty() {
if (this.head === null) {
console.log(true)
} else {
console.log(false)
}
}
listSize() {
console.log(this.size)
}
printList() {
var cur = this.head
var str = ''
while (cur) {
str += cur.element + ' '
cur = cur.next
}
console.log(str)
}
}
const ll = new SinglyLinkedList()
// ll.isListEmpty()
// ll.listSize()
ll.addToEnd(1)
ll.addToHead(5)
ll.addToHead(4)
ll.addToHead(4)
ll.addToEnd(1)
ll.printList()
ll.deleteFrom(0)
// ll.isListEmpty()
ll.listSize()
ll.printList()
ll.reverseList()
ll.printList()