Skip to content

Commit 07b1cec

Browse files
committed
Fix linked-list bugs
In section 17, session 10: - insertLast() crashed if the list was empty - getAt() kept going after finding the requested node - removeAt() crashed if the argument equaled the number of nodes - printListData() added a trailing space separator
1 parent 4ab271a commit 07b1cec

File tree

1 file changed

+14
-3
lines changed
  • 17-iterators-data-structures/10-linked-lists

1 file changed

+14
-3
lines changed

17-iterators-data-structures/10-linked-lists/script.js

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,13 @@ class LinkedList {
2121

2222
// Insert last node (Tail)
2323
insertLast(value) {
24+
25+
// Don't assume the list isn't empty.
26+
if (!this._head) {
27+
this.insertFirst(value);
28+
return;
29+
}
30+
2431
const newNode = new Node(value);
2532
let current = this._head;
2633

@@ -66,6 +73,7 @@ class LinkedList {
6673
while (current) {
6774
if (count === index) {
6875
console.log(current._value);
76+
break;
6977
}
7078
count++;
7179
current = current.next;
@@ -75,7 +83,7 @@ class LinkedList {
7583

7684
// Remove at index
7785
removeAt(index) {
78-
if (index > this._length) {
86+
if (index >= this._length) {
7987
return;
8088
}
8189

@@ -101,10 +109,12 @@ class LinkedList {
101109
printListData() {
102110
let current = this._head;
103111
let list = '';
112+
let separator = '';
104113

105114
while (current) {
106-
list += current._value + ' ';
115+
list += separator + current._value;
107116
current = current.next;
117+
separator = ' ';
108118
}
109119

110120
console.log(list);
@@ -119,7 +129,8 @@ class LinkedList {
119129

120130
const list = new LinkedList();
121131

122-
list.insertFirst(100);
132+
list.insertLast(100);
133+
list.removeAt(1); // Nothing to remove
123134
list.insertFirst(200);
124135
list.insertFirst(300);
125136
list.insertLast(50);

0 commit comments

Comments
 (0)