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

Class LinkedList

chapter02/util/LinkedListX.js:23–138  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

21 }
22
23 class LinkedList {
24 constructor() {
25 this.head = null;
26 this.tail = null;
27 }
28
29 append(value) {
30 let node = new Node(value);
31 // if list is empty
32 if (!this.head) {
33 this.head = node;
34 this.tail = node;
35 }
36 else {
37 this.tail.next = node;
38 this.tail = node;
39 }
40 }
41
42 prepend(value) {
43 let node = new Node(value);
44 node.next = this.head;
45 this.head = node;
46 }
47
48 pop() {
49 let cur = this.head;
50
51 // only one or no item exists
52 if (!cur) return null;
53 if (!cur.next) {
54 this.head = null;
55 return cur;
56 }
57 // move till the 2nd last
58 while (cur.next.next)
59 cur = cur.next;
60
61 let last = this.tail;
62 this.tail = cur;
63 this.tail.next = null;
64 return last;
65 }
66
67 popFirst() {
68 let first = this.head;
69 if (this.head && this.head.next) {
70 this.head = this.head.next;
71 first.next = null;
72 }
73 else this.head = null;
74 return first;
75 }
76
77 head() {
78 return this.head;
79 }
80

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected