有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我在读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) 个答案

  1. # 1 楼答案

    不,不是current.next = current.next.prevcurrent.next = current,而current.prev = current.prev.nextcurrent.prev = current。请附加调试器并按照代码查找错误和正确的解决方案。我们不会在这里给你做作业

  2. # 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;
    }