MCPcopy Create free account
hub / github.com/careercup/CtCI-6th-Edition-JavaScript / LinkedList

Class LinkedList

chapter07/util/LinkedList.js:10–125  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

8 }
9
10 class LinkedList {
11 constructor() {
12 this.head = null;
13 this.tail = null;
14 }
15
16 append(value) {
17 let node = new Node(value);
18 // if list is empty
19 if (!this.head) {
20 this.head = node;
21 this.tail = node;
22 }
23 else {
24 this.tail.next = node;
25 this.tail = node;
26 }
27 }
28
29 prepend(value) {
30 let node = new Node(value);
31 node.next = this.head;
32 this.head = node;
33 }
34
35 pop() {
36 let cur = this.head;
37
38 // only one or no item exists
39 if (!cur) return null;
40 if (!cur.next) {
41 this.head = null;
42 return cur;
43 }
44 // move till the 2nd last
45 while (cur.next.next)
46 cur = cur.next;
47
48 let last = this.tail;
49 this.tail = cur;
50 this.tail.next = null;
51 return last;
52 }
53
54 popFirst() {
55 let first = this.head;
56 if (this.head && this.head.next) {
57 this.head = this.head.next;
58 first.next = null;
59 }
60 else this.head = null;
61 return first;
62 }
63
64 head() {
65 return this.head;
66 }
67

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected