2017-07-25 13 views
-2

我正在爲我的大學任務創建一個散列函數。我的散列函數的工作原理是這樣的......它將一個字符串作爲輸入,並將每個字符的ASCII值添加到一個名爲sum的整數變量中。這在名爲hash_func的函數中完成。然後在名爲MYHashfunc的函數中,我使用了遞歸來減少sum的值,使得它的值可以小於使用我的散列函數存儲數據的數組的大小。由於我使用單獨的鏈接方法來解決衝突,我使用了一個LinkedList數組。 但是,當函數hash_func在MYhashfunc中被調用時,我得到了一個堆棧溢出錯誤。代碼如下: -我在散列函數代碼中得到一個StackOverflow錯誤,但我無法確定,有人可以幫我修復它/

package hashfunction; 

import java.util.LinkedList; 
import java.util.Scanner; 

public class Hashfunction { 

public static int MyhashFUNC(String str,int A){ 
    int X=0; 
    int sum = hash_func(str); 
    if(sum<A) 
     return sum; 
    else{ 
     X = X+sum%10; 
     sum /= 10; 
     return(MyhashFUNC(str, A)); 
    } 
} 

public static int hash_func(String str) { 
    int sum = 0; 
    int len = str.length(); 
    for (int i = 0; i < len; i++) { 
     if (str.charAt(i) >= '0' && str.charAt(i) <= '9') { 
      sum += (int) str.charAt(i); 
     } else if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z' || 
     str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') { 
      sum += (int) str.charAt(i); 
     } 
    } 
    return sum; 
} 

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 
    int N; 
    int z; 
    N = sc.nextInt(); 
    String[] str_array = new String[N]; 
    LinkedList<String>[] l_list = new LinkedList[N]; 
    for (int i = 0; i < N; i++) { 
     l_list[i] = new LinkedList<String>(); 
    } 
    for (int i = 0; i < N; i++) { 
     str_array[i] = sc.next(); 
    } 
    for (int i = 0; i < N; i++) { 
     z = MyhashFUNC(str_array[i],N); 
     if(l_list[z].peek()!="-1"){ 
       l_list[z].set(z, str_array[i]); 
     } 
     else{ 
      l_list[z].add(str_array[i]); 
     } 
    } 

    for (int i = 0; i < N; i++) { 
     int size = l_list[i].size(); 
      for (int j = 0; j < size; j++) { 
       System.out.println(l_list[i].get(j)); 
     } 
    } 
} 
} 
+4

這兩個輸入都不會被修改。爲什麼它會停止遞歸? – shmosel

+0

您能否詳細解釋一下 –

回答

3

在如果你sum >= a進入else塊,你再打電話使用相同的參數相同的方法,該方法

public static int MyhashFUNC(String str,int A){ 
    int X=0; 
    int sum = hash_func(str); 
    if(sum<A) 
     return sum; 
    else{ 
     X = X+sum%10; 
     sum /= 10; 
     return(MyhashFUNC(str, A)); // Call again MyhashFUNC with same parameters 
    } 
} 

。這將生成StackOverFlow

2

這裏的問題:看看換取你的函數:

return(MyhashFUNC(str, A)); 

它一而再,再而再次調用自身,沒有任何事情來阻止它。您一直向調用堆棧添加堆棧幀,直到獲得 - 等待它 - 堆棧溢出。

這是沒有停止條件的遞歸標誌。

+0

謝謝,我犯了這麼一個愚蠢的錯誤。我沒有注意到'sum'的值保持不變 –

2

問題是, 這是遞歸函數,所以在每次遞歸調用時,您的輸入參數都應該改變/不同/更新。

public static int MyhashFUNC(String str,int A){ 
    int X=0; 
    int sum = hash_func(str); 
    if(sum<A) 
     return sum; 
    else{ 
     X = X+sum%10; 
     sum /= 10; 
     return(MyhashFUNC(str, A));//you are not updating any value and calling same function recursively. this will cause StackOverflowError. 
    } 
} 
+0

是的,謝謝我已經解決了我的問題:) –

相關問題