我需要使用遞歸編寫一個contains方法,這意味着查找是否在其中一個節點中存在「元素」。如何使用遞歸編寫鏈表的包含方法? java
public class SortedSetNode implements Set
{
protected String value;
protected SortedSetNode next;
}
public boolean contains(String el) {
if (next.getValue().equals(el))
{
return true;
}
else
{
next.contains(el);
}
}
你可能需要重寫你的'contains'方法看到,因爲你的類實現'java.util.set'和類有一個'contains'方法以及 – smac89
在這種情況下使用遞歸是一個奇怪的要求:如果列表足夠大,並且該項目接近結尾,則將得到一個StackOverflowError(10k個元素應該足以打破它)... – assylias