From 55c114df2e999d2c9d4be56761934a3c9c993043 Mon Sep 17 00:00:00 2001 From: Ian Cowan <38896380+iccowan@users.noreply.github.com> Date: Tue, 2 Nov 2021 15:28:00 -0400 Subject: [PATCH] Add doubly linked list print reverse (#2797) --- DataStructures/Lists/DoublyLinkedList.java | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/DataStructures/Lists/DoublyLinkedList.java b/DataStructures/Lists/DoublyLinkedList.java index dc50945b5..a3a0bcba9 100644 --- a/DataStructures/Lists/DoublyLinkedList.java +++ b/DataStructures/Lists/DoublyLinkedList.java @@ -271,6 +271,18 @@ public class DoublyLinkedList { } System.out.println(); } + + /** + * Prints the contents of the list in reverse order + */ + public void displayBackwards() { + Link current = tail; + while (current != null) { + current.displayLink(); + current = current.previous; + } + System.out.println(); + } } /** @@ -311,15 +323,19 @@ class Link { myList.insertHead(7); myList.insertHead(10); myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) --> + myList.displayBackwards(); myList.insertTail(11); myList.display(); // <-- 10(head) <--> 7 <--> 13 <--> 11(tail) --> + myList.displayBackwards(); myList.deleteTail(); myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) --> + myList.displayBackwards(); myList.delete(7); myList.display(); // <-- 10(head) <--> 13(tail) --> + myList.displayBackwards(); myList.insertOrdered(23); myList.insertOrdered(67); @@ -327,12 +343,15 @@ class Link { myList.display(); // <-- 3(head) <--> 10 <--> 13 <--> 23 <--> 67(tail) --> myList.insertElementByIndex(5, 1); myList.display(); // <-- 3(head) <--> 5 <--> 10 <--> 13 <--> 23 <--> 67(tail) --> - + myList.displayBackwards(); myList.reverse(); // <-- 67(head) <--> 23 <--> 13 <--> 10 <--> 5 <--> 3(tail) --> myList.display(); + myList.clearList(); myList.display(); + myList.displayBackwards(); myList.insertHead(20); myList.display(); + myList.displayBackwards(); } }