2013-09-21 48 views
0

我需要使用遞歸編寫一個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); 
     } 

    } 
+0

你可能需要重寫你的'contains'方法看到,因爲你的類實現'java.util.set'和類有一個'contains'方法以及 – smac89

+0

在這種情況下使用遞歸是一個奇怪的要求:如果列表足夠大,並且該項目接近結尾,則將得到一個StackOverflowError(10k個元素應該足以打破它)... – assylias

回答

0

well next.contains(el),只是在此之前添加return語句!

if (value.equals(el)) { 
    return true; 
} 

return next.contains(el); 

當然,你要處理的時候next是無效的和(即你在最後一個元素),然後返回false。

+0

如果next_爲null(未找到字符串),它將拋出NullPointerException – alfasin

+0

這就是爲什麼有我的答案的最後一句:) – coyotte508

+0

我已更正爲此: '公共布爾包含(String el){' \t \t'if(next!= null)' \t'{ \t \t return false; \t} \t否則,如果(next.getValue()等於(EL)) \t { \t \t迴歸真實; \t} \t其他 \t { \t \t回next.contains致發光(EL); \t} \t }' – lauraxx

0
public boolean contains(String el) { 
    if (value.equals(el)) return true; 
    if (next == null) return false; 
    else return next.contains(el); 
} 
+1

return'false' not'dalse' – smac89

+0

@ Smac89 - 他可能已經將'dalse'定義爲一個常量:-) –

+0

@StephenC ahh的確如此。但常量應該大寫? – smac89

相關問題