【发布时间】:2020-04-18 08:14:05
【问题描述】:
以递归方式实现LinkedList 对我来说有点挑战,我在实现其remove 方法时遇到了困难,想知道如何以递归方式保持对前一项的引用?
MyLinkedList 类
package linkedlist;
public class MyLinkedList {
private Integer value;
private MyLinkedList next;
public MyLinkedList() {
}
public MyLinkedList(Integer value) {
this.value = value;
}
public void add(Integer value) {
if (this.value == null) {
this.value = value;
} else if (this.next == null) {
this.next = new MyLinkedList(value);
} else {
this.next.add(value);
}
}
public MyLinkedList remove(Integer index) {
//
// if (index < 0) {
// return this;
// }
// if (index == 0) {
// return this.next;
// }
// this.next = remove(index - 1);
return this;
}
public Integer indexOf(Integer value) {
if (this.value.equals(value)) {
return 0;
} else if (this.next == null) {
return null;
} else {
return 1 + this.next.indexOf(value);
}
}
}
MyLinkedListTester 类
package linkedlist;
public class MyLinkedListTester {
public static void main(String[] args) {
MyLinkedList myLinkedList = new MyLinkedList();
myLinkedList.add(1);
myLinkedList.add(2);
myLinkedList.add(3);
myLinkedList.add(4);
System.out.println("Index Of Array: " + myLinkedList.indexOf(3));
MyLinkedList linkedList = myLinkedList.remove(3);
}
}
【问题讨论】:
-
啊,这样比较好。对我来说,第一个想法是创建另一个方法
private remove(MyLinkedList previous, int index),它是从remove(int index)方法调用的。然后可以递归地使用该方法。我不会使用Integer,除非确实需要(可为空!)对象引用。当然也可以创建双链表,但也可能超出范围。 -
感谢您递归删除的想法。但是,在您的情况下,迭代方法是最简单和最有效的选择。
标签: java recursion linked-list singly-linked-list