-2

私には2つのクラスがListNodeありMyListます。

ListNode:

public class ListNode {
    private String str;
    private ListNode next;
    public ListNode(String str) {
        this.str = str;
        next = null;
    }
    public String getString() {
        return str;
    }
    public ListNode getNext() {
        return next;
    }
    public void setNext(ListNode next) {
        this.next = next;
    }
}

私のリスト

public MyList RecReverse() { //my attempt at the recursive method
    if (head.getNext() == null) {
        return this;
    }
    MyList remainder = new MyList();
    remainder.head = head.getNext(); //start rest of list at the 2nd thing
    ListNode temp = new ListNode(head.getString()); //get the first thing in list
    temp.setNext(null); //set to null to indicate end of list

    remainder.RecReverse(); //reverse the remaining things in the list
    remainder.head.setNext(temp); //then add it to the end of the reversed list

    return remainder;



}

ご覧のとおり、MyListクラスにはListNode使用する必要のある変数があります。RecReverseメソッドは引数を取らず、オブジェクトを返す必要がありMyListます。このメソッドは関数も使用する必要がありますRev(L) = Rev(L`).x。ここL`で、はリストの残りの部分であり、はリストxの最初のものです。

現在、リストを逆にして印刷すると、次のようにしか印刷されません。

2

1

コンソールで

4

2 に答える 2

2
public MyList RecReverse() { //my attempt at the recursive method
    if (head.getNext() == null) {
        return this;
    }

    MyList remainder = new MyList();
    remainder.head = head.getNext(); // New list has rest of this list (after head)
    ListNode temp = new ListNode(head.getString()); // save the first thing in list

    remainder = remainder.RecReverse(); //reverse the things in the new 2nd part list

    remainder.end().setNext(temp); // put old head on the end

    return remainder;

}

private ListNode end() {
    ListNode curr = head;
    while (curr.getNext() != null) {
        curr = curr.getNext();
    }
    return curr;
}
于 2013-01-30T00:04:18.323 に答える
1

どうにかして元のリストの末尾を保持できれば、正しい結果が得られます。問題は、各再帰呼び出しで正しいリストを組み立てるが、2 つの要素を含むリストを返すことです。正しい解決策については、Lee Meador の回答を参照してください。リスト構造の最後を保持すると、最適化できます。

于 2013-01-30T00:10:08.493 に答える