@@ -218,6 +218,34 @@ public static void removeDuplicates(DoublyLinkedList l) {
218
218
}
219
219
}
220
220
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
+
221
249
/** Clears List */
222
250
public void clearList () {
223
251
head = null ;
@@ -299,6 +327,9 @@ public static void main(String args[]) {
299
327
myList .display (); // <-- 3(head) <--> 10 <--> 13 <--> 23 <--> 67(tail) -->
300
328
myList .insertElementByIndex (5 , 1 );
301
329
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 ();
302
333
myList .clearList ();
303
334
myList .display ();
304
335
myList .insertHead (20 );
0 commit comments