@@ -218,6 +218,34 @@ public static void removeDuplicates(DoublyLinkedList l) {
218218 }
219219 }
220220
221+ /**
222+ * Reverses the list in place
223+ *
224+ * @param l the DoublyLinkedList to reverse
225+ */
226+ public void reverse () {
227+ // Keep references to the head and tail
228+ Link thisHead = this .head ;
229+ Link thisTail = this .tail ;
230+
231+ // Flip the head and tail references
232+ this .head = thisTail ;
233+ this .tail = thisHead ;
234+
235+ // While the link we're visiting is not null, flip the
236+ // next and previous links
237+ Link nextLink = thisHead ;
238+ while (nextLink != null ) {
239+ Link nextLinkNext = nextLink .next ;
240+ Link nextLinkPrevious = nextLink .previous ;
241+ nextLink .next = nextLinkPrevious ;
242+ nextLink .previous = nextLinkNext ;
243+
244+ // Now, we want to go to the next link
245+ nextLink = nextLinkNext ;
246+ }
247+ }
248+
221249 /** Clears List */
222250 public void clearList () {
223251 head = null ;
@@ -299,6 +327,9 @@ public static void main(String args[]) {
299327 myList .display (); // <-- 3(head) <--> 10 <--> 13 <--> 23 <--> 67(tail) -->
300328 myList .insertElementByIndex (5 , 1 );
301329 myList .display (); // <-- 3(head) <--> 5 <--> 10 <--> 13 <--> 23 <--> 67(tail) -->
330+
331+ myList .reverse (); // <-- 67(head) <--> 23 <--> 13 <--> 10 <--> 5 <--> 3(tail) -->
332+ myList .display ();
302333 myList .clearList ();
303334 myList .display ();
304335 myList .insertHead (20 );
0 commit comments