forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverseDoubleLinkedList.java
50 lines (43 loc) · 1.2 KB
/
ReverseDoubleLinkedList.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.rampatra.linkedlists;
import com.rampatra.base.DoubleLinkedList;
import com.rampatra.base.DoubleLinkedNode;
/**
* Created by IntelliJ IDEA.
*
* @author rampatra
* @since 6/19/15
* @time: 9:24 AM
*/
public class ReverseDoubleLinkedList {
/**
* Reverses the doubly linked list.
*
* @param list
*/
public static <E extends Comparable<E>> void reverseList(DoubleLinkedList<E> list) {
DoubleLinkedNode<E> curr = list.getNode(0);
DoubleLinkedNode<E> temp = curr;
while (curr != null) {
temp = curr.prev;
curr.prev = curr.next;
curr.next = temp;
curr = curr.prev;
}
// temp will be null if linked list has only one node
if (temp != null) {
list.head = temp.prev;
}
}
public static void main(String[] args) {
DoubleLinkedList<Integer> linkedList = new DoubleLinkedList<>();
linkedList.add(11);
linkedList.add(22);
linkedList.add(33);
linkedList.add(44);
linkedList.add(55);
linkedList.add(66);
linkedList.printList();
reverseList(linkedList);
linkedList.printList();
}
}