2016-12-02 70 views
-1

我正在阅读有关java实现中的队列。我要实现以下任务:颠倒整个列表的顺序为双向linkedList

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

我这样做对吗? 谢谢

+0

不会如预期你有工作吗? – dave823

+2

'扔新'...失去了一些东西。 – AxelH

+0

https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html – xenteros

回答

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

非常感谢你的兄弟:)上帝保佑你 – Joe

+0

我还有一个问题:看看这段代码:public class ArrayQueue {private String [] a; private int N;私人诠释回来;私人诠释前沿; public boolean isEmpty(){return a.length == 0; }我的isEmpty()方法是否正确?谢谢 – Joe

+0

这应该是在其他帖子,但乍一看,我宁愿返回N == 0 –

2

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