Skip to content

Commit 6e85c11

Browse files
authored
Create LinkedList.js
0 parents  commit 6e85c11

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

LinkedList.js

+88
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
const Node = require('./Node');
2+
3+
class LinkedList {
4+
constructor() {
5+
this.head = null;
6+
}
7+
8+
addToHead(data) {
9+
const newHead = new Node(data);
10+
const currentHead = this.head;
11+
this.head = newHead;
12+
if (currentHead) {
13+
this.head.setNextNode(currentHead);
14+
}
15+
}
16+
17+
addToTail(data) {
18+
let tail = this.head;
19+
if (!tail) {
20+
this.head = new Node(data);
21+
} else {
22+
while (tail.getNextNode() !== null) {
23+
tail = tail.getNextNode();
24+
}
25+
tail.setNextNode(new Node(data));
26+
}
27+
}
28+
29+
removeHead() {
30+
const removedHead = this.head;
31+
if (!removedHead) {
32+
return;
33+
}
34+
this.head = removedHead.getNextNode();
35+
return removedHead.data;
36+
}
37+
38+
printList(){
39+
let currentNode = this.head;
40+
let output = '<head> ';
41+
while (currentNode !== null){
42+
output += currentNode.data + ' ';
43+
currentNode = currentNode.getNextNode();
44+
}
45+
output += '<tail>';
46+
console.log(output);
47+
}
48+
} // end LinkedList class
49+
50+
51+
52+
module.exports = LinkedList;
53+
54+
55+
56+
/*
57+
A linked list is a sequential chain of nodes, each of which
58+
contains two elements: data and a link to the next node.
59+
Uses nodes from Node class in Node.js.
60+
61+
addToHead(data):
62+
takes one parameter called data. Inside the method, create
63+
a Node const variable named newHead, and pass data as an argument.
64+
It checks if there is a current head to the list. If there is,
65+
it set the list’s head’s next node to currentHead.
66+
67+
addToTail(data):
68+
takes one parameter called data and starts with a variable tail
69+
set equal to the list’s head. If there is no head, that means that
70+
the list is empty, and we will be creating the head and tail with
71+
the data passed in. Otherwise, we will iterate through the list until
72+
we find the last node (current tail) and we will add a pointer
73+
from that node to our new tail.
74+
75+
removeHead()
76+
takes no parameters. Sets variable removedHead to the list’s
77+
original head to keep track of it. It checks to see if the list
78+
had a head. If it doesn’t it returns nothing. If there is a head,
79+
it will remove it by setting the list’s head equal to the original
80+
head’s next node, and then return that original head data.
81+
82+
printList()
83+
creates a String (output) that holds the data from every node
84+
in the list starting at the list’s head set to variable currentNode.
85+
It iterates through the list adding currentNode's data and a ' ' to
86+
output and then updating currentNode to its next node. It does it
87+
while currentNode doesn’t equal null.
88+
*/

0 commit comments

Comments
 (0)