Skip to content

Commit 55c114d

Browse files
authored
Add doubly linked list print reverse (TheAlgorithms#2797)
1 parent b05b4d0 commit 55c114d

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

DataStructures/Lists/DoublyLinkedList.java

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,18 @@ public void display() { // Prints contents of the list
271271
}
272272
System.out.println();
273273
}
274+
275+
/**
276+
* Prints the contents of the list in reverse order
277+
*/
278+
public void displayBackwards() {
279+
Link current = tail;
280+
while (current != null) {
281+
current.displayLink();
282+
current = current.previous;
283+
}
284+
System.out.println();
285+
}
274286
}
275287

276288
/**
@@ -311,28 +323,35 @@ public static void main(String args[]) {
311323
myList.insertHead(7);
312324
myList.insertHead(10);
313325
myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) -->
326+
myList.displayBackwards();
314327

315328
myList.insertTail(11);
316329
myList.display(); // <-- 10(head) <--> 7 <--> 13 <--> 11(tail) -->
330+
myList.displayBackwards();
317331

318332
myList.deleteTail();
319333
myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) -->
334+
myList.displayBackwards();
320335

321336
myList.delete(7);
322337
myList.display(); // <-- 10(head) <--> 13(tail) -->
338+
myList.displayBackwards();
323339

324340
myList.insertOrdered(23);
325341
myList.insertOrdered(67);
326342
myList.insertOrdered(3);
327343
myList.display(); // <-- 3(head) <--> 10 <--> 13 <--> 23 <--> 67(tail) -->
328344
myList.insertElementByIndex(5, 1);
329345
myList.display(); // <-- 3(head) <--> 5 <--> 10 <--> 13 <--> 23 <--> 67(tail) -->
330-
346+
myList.displayBackwards();
331347
myList.reverse(); // <-- 67(head) <--> 23 <--> 13 <--> 10 <--> 5 <--> 3(tail) -->
332348
myList.display();
349+
333350
myList.clearList();
334351
myList.display();
352+
myList.displayBackwards();
335353
myList.insertHead(20);
336354
myList.display();
355+
myList.displayBackwards();
337356
}
338357
}

0 commit comments

Comments
 (0)