颠倒双向链表的整个列表的顺序
reverse the order of the entire list for doubly linkedList
我正在阅读 java 实现中的队列。我要执行以下任务:
public class DoublyLinkedList
{
private Node first; // the first Node in the list
private Node last; // the last Node in the list
private class Node
{
private Point p;
private Node prev; // the previous Node
private Node next; // the next Node
}
public void reverse()
{
// your code
}
}
我喜欢这个:
public void reverse() { // that reverses the order of the entire list
if (first == null && last == null) {
throw new RuntimeException();
}
Node current = first;
while (current!=null) {
current.next= current.next.prev;
current.prev=current.prev.next;
current=current.next;
}
}
我做的对吗?
谢谢
不,不是。 current.next = current.next.prev
类似于 current.next = current
,current.prev = current.prev.next
类似于 current.prev = current
。请附加调试器并按照您的代码查找错误和正确的解决方案。我们不会在这里做你的功课。 ;-)
您没有更改代码中的第一个和最后一个指针。如果列表为空,为什么要抛出异常?
我想我会做类似的事情:
public void reverse()
{
Node current = first;
while (current != null) {
Node next = current.next;
current.next = current.prev;
current.prev = next;
current = next;
}
Node temp = first;
first = last;
last = temp;
}
我正在阅读 java 实现中的队列。我要执行以下任务:
public class DoublyLinkedList
{
private Node first; // the first Node in the list
private Node last; // the last Node in the list
private class Node
{
private Point p;
private Node prev; // the previous Node
private Node next; // the next Node
}
public void reverse()
{
// your code
}
}
我喜欢这个:
public void reverse() { // that reverses the order of the entire list
if (first == null && last == null) {
throw new RuntimeException();
}
Node current = first;
while (current!=null) {
current.next= current.next.prev;
current.prev=current.prev.next;
current=current.next;
}
}
我做的对吗? 谢谢
不,不是。 current.next = current.next.prev
类似于 current.next = current
,current.prev = current.prev.next
类似于 current.prev = current
。请附加调试器并按照您的代码查找错误和正确的解决方案。我们不会在这里做你的功课。 ;-)
您没有更改代码中的第一个和最后一个指针。如果列表为空,为什么要抛出异常?
我想我会做类似的事情:
public void reverse()
{
Node current = first;
while (current != null) {
Node next = current.next;
current.next = current.prev;
current.prev = next;
current = next;
}
Node temp = first;
first = last;
last = temp;
}