リストの末尾に要素を追加するメソッドaddLastを以下の宣言でListクラスに作成せよ.
void addLast(String s) { ... }
addLastは以下のように使用できる.
/*
* test addLast
*/
public class Test3 {
public static void main(String args[]) {
List a = new List();
a.addLast("A");
a.addLast("B");
a.addLast("C");
a.print();
}
}
nodat000% java Test3 A B C nodat000%
ListNode lastNode(ListNode node) {
if(node.next == null) {
return node;
} else {
return lastNode(node.next);
}
}
void addLast(String s) {
if(top == null) {
top = new ListNode(s);
} else {
ListNode last;
last = lastNode(top);
last.next = new ListNode(s);
}
}
void addLast(String s) {
top = addLastRecursive(top, s);
}
ListNode addLastRecursive(ListNode node, String s) {
if(node == null)
return new ListNode(s);
node.next = addLastRecursive(node.next, s);
return node;
}