反转双链表的整个列表的顺序

时间:2016-12-02 13:40:59

标签: java doubly-linked-list

我正在阅读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;
    }  
}

我做对了吗? 感谢

2 个答案:

答案 0 :(得分:2)

不,不是。 jQuerycurrent.next = current.next.prev类似,current.next = currentcurrent.prev = current.prev.next类似。请附上调试器并按照您的代码查找错误和正确的解决方案。我们不会在这里做你的功课。 ; - )

答案 1 :(得分:2)

您不能更改代码中的第一个和最后一个指针。如果列表为空,为什么要抛出异常?

我想我会做类似的事情:

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;
}