Reputation: 43
I'm attempting to implement a reverse() function on a circular doubly linked list.
Here is my code:
public void reverseCDLL() {
if (head != null) {
Node current = head, next, temp;
do{
next = current.getNextNode();
temp = current.getPrevNode();
current.setPrevNode(current.getNextNode());
current.setNextNode(temp);
current = next;
}while(current != head);
}
}
Input: 1 2 3 4
Output: 1 4 3 2
Expected Output: 4 3 2 1
I'm very close to finishing this but one little thing is wrong and I just can't pin point what it is.
Any assistance / hints would be greatly appreciated.
Upvotes: 2
Views: 1172
Reputation: 3302
The algorithm works fine, you just need to change the head pointer to the correct value. When you reverse a linked list the head points to the last node, similarly in this case too the head should point to the last node.
public void reverseCDLL() {
if (head != null) {
Node current = head, next, temp;
do{
next = current.getNextNode();
temp = current.getPrevNode();
current.setPrevNode(current.getNextNode());
current.setNextNode(temp);
current = next;
}while(current != head);
head = head.getNextNode();
}
}
Upvotes: 3