私には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
コンソールで