Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit5b261e9

Browse files
authored
Add algorithm to reverse doubly linked list (TheAlgorithms#2796)
1 parent9e36810 commit5b261e9

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

‎DataStructures/Lists/DoublyLinkedList.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
publicvoidreverse() {
227+
// Keep references to the head and tail
228+
LinkthisHead =this.head;
229+
LinkthisTail =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+
LinknextLink =thisHead;
238+
while (nextLink !=null) {
239+
LinknextLinkNext =nextLink.next;
240+
LinknextLinkPrevious =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
publicvoidclearList() {
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

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp