2016-12-02 12 views
-1

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

私が右のでしょうか? ありがとう

+0

が期待どおりに仕事を持っているものでしょうか? – dave823

+2

'throw new' ...そこに何かがありません。 – 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;プライベートint N;プライベートintバック。プライベートintフロント; public boolean isEmpty(){a.length == 0を返します。 } isEmpty()メソッドは正しいですか?ありがとう – Joe

+0

これは他の投稿にあるはずですが、一見すると、私はむしろN == 0を返します。 –

2

いいえ。 current.next = current.next.prevcurrent.next = currentcurrent.prev = current.prev.nextcurrent.prev = currentと同じです。デバッガを接続し、エラーと適切な解決策を見つけるためにあなたのコードに従ってください。ここで宿題はしません。 ;-)

関連する問題