Skip to content

Commit baecf77

Browse files
committed
Issue williamfiset#133 solved together with test cases for toString() method in DoublyLinkedList data structure
1 parent 07e8427 commit baecf77

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

src/main/java/com/williamfiset/algorithms/datastructures/linkedlist/DoublyLinkedList.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -287,7 +287,10 @@ public String toString() {
287287
sb.append("[ ");
288288
Node<T> trav = head;
289289
while (trav != null) {
290-
sb.append(trav.data + ", ");
290+
sb.append(trav.data);
291+
if (trav.next != null) {
292+
sb.append(", ");
293+
}
291294
trav = trav.next;
292295
}
293296
sb.append(" ]");

src/test/java/com/williamfiset/algorithms/datastructures/linkedlist/LinkedListTest.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,21 @@ public void testRandomizedIndexOf() {
309309
}
310310
}
311311

312+
@Test
313+
public void testToString() {
314+
DoublyLinkedList<String> strs = new DoublyLinkedList<>();
315+
assertEquals(strs.toString(), "[ ]");
316+
strs.add("a");
317+
assertEquals(strs.toString(), "[ a ]");
318+
strs.add("b");
319+
assertEquals(strs.toString(), "[ a, b ]");
320+
strs.add("c");
321+
strs.add("d");
322+
strs.add("e");
323+
strs.add("f");
324+
assertEquals(strs.toString(), "[ a, b, c, d, e, f ]");
325+
}
326+
312327
// Generate a list of random numbers
313328
static List<Integer> genRandList(int sz) {
314329
List<Integer> lst = new ArrayList<>(sz);

0 commit comments

Comments
 (0)