[英]Reversing a circular doubly linked list
I'm attempting to implement a reverse() function on a circular doubly linked list.我正在尝试在循环双向链表上实现 reverse() 函数。
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
输入:
1 2 3 4
Output: 1 4 3 2
输出:
1 4 3 2
Expected Output: 4 3 2 1
预期产出:
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.任何帮助/提示将不胜感激。
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.