2017-02-23 6 views
0

私はSinglyLinkedListクラスの中に以下のインスタンス変数を持っています。私がやりたい何クラスメソッド内でリンクリストを再帰的に返す

/* head is a reference to the front of the list (first element) 
* by default, head is initialized to null */ 
private Node head; 

/* tail is a reference to the back of the list (last element) 
* by default, tail is initialized to null */ 
private Node tail; 

/* length is an integer that represents the size of our list, 
* by default it is assigned a value of 0 */ 
protected int length; 

は、再帰的にSinglyLinkedListオブジェクトを反転させるrecursiveReverse()と呼ばれる方法を記述しています。このようなlist.recursiveReverse()

ように私はこれがあなたのために働く必要があるNodeオブジェクト

public SinglyLinkedList recursiveReverse() { 
    static Node temp = head; 
    if(temp == null) return null; 
    if(length == 1) return this; 

    Node temp_2 = temp.next; 
    temp.next = null; 
    // here is where i am stuck with the recursive call 
    // is passing a Node as an argument the only way ? 
    // if so, then how do I pass it in a class method ? 
    // make the method static ? 
} 
+0

あなたは、静的としてメソッド内の変数を宣言した - 何がやろうとしていますか?それはコンパイルされず、静的にする必要もありません。 –

答えて

1

に通過することなく動作していないよういくつかのアイデアを持っています。

public ListNode reverseList(ListNode head) { 
    if(head==null || head.next == null) 
     return head; 

    //get second node  
    ListNode second = head.next; 
    //set first's next to be null 
    head.next = null; 

    ListNode rest = reverseList(second); 
    second.next = head; 

    return rest; 
} 

参考:Reverse a Singly Linked List.

関連する問題