Skip to content

Create a method to reverse a doubly linked list #2796

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 1, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions DataStructures/Lists/DoublyLinkedList.java
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,34 @@ public static void removeDuplicates(DoublyLinkedList l) {
}
}

/**
* Reverses the list in place
*
* @param l the DoublyLinkedList to reverse
*/
public void reverse() {
// Keep references to the head and tail
Link thisHead = this.head;
Link thisTail = this.tail;

// Flip the head and tail references
this.head = thisTail;
this.tail = thisHead;

// While the link we're visiting is not null, flip the
// next and previous links
Link nextLink = thisHead;
while (nextLink != null) {
Link nextLinkNext = nextLink.next;
Link nextLinkPrevious = nextLink.previous;
nextLink.next = nextLinkPrevious;
nextLink.previous = nextLinkNext;

// Now, we want to go to the next link
nextLink = nextLinkNext;
}
}

/** Clears List */
public void clearList() {
head = null;
Expand Down Expand Up @@ -299,6 +327,9 @@ public static void main(String args[]) {
myList.display(); // <-- 3(head) <--> 10 <--> 13 <--> 23 <--> 67(tail) -->
myList.insertElementByIndex(5, 1);
myList.display(); // <-- 3(head) <--> 5 <--> 10 <--> 13 <--> 23 <--> 67(tail) -->

myList.reverse(); // <-- 67(head) <--> 23 <--> 13 <--> 10 <--> 5 <--> 3(tail) -->
myList.display();
myList.clearList();
myList.display();
myList.insertHead(20);
Expand Down