[英]How to fix String linkedlist implementation?
我在 java 中實現了這種存儲類型的字符串結構,到目前為止沒問題,這已經是一件簡單的事情,但盡管有困難,但我沒有意識到缺少什么?
插入 function 可以工作,但是搜索和顯示 function 不能以正確的方式工作,總是返回“0”實際上一切看起來都很准確,所以很奇怪我寫了非常相似的代碼塊作為通用類型,我沒有考慮關鍵的區別。
在下面
package ds_project;
public class SLL_String {
StringNode tail;
int wordCounter = 0;
public void insert(String insertKey) {
StringNode myhead = new StringNode();
if (tail == null) {
myhead.setData(insertKey);
} else {
myhead.setData(insertKey);
myhead.setLink(tail);
tail = myhead;
}
}
public int search(String key) {
StringNode head = tail;
while (head != null) {
if (head.getData().equals(key)) {
wordCounter++;
}
head = head.getLink();
}
System.out.println(wordCounter);
return wordCounter;
}
public void displayString() {
StringNode head = tail;
if (head != null) {
while (head != null) {
System.out.print(head.getData() + "::" + search(head.getData()));
head = head.getLink();
}
}
}
}
package ds_project;
public class StringNode {
private StringNode Link;
private String data;
public StringNode() {
}
public StringNode getLink() {
return Link;
}
public void setLink(StringNode Link) {
this.Link = Link;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
您的列表無法增長。 嘗試這個:
public void insert(String insertKey) {
StringNode myhead = new StringNode();
myhead.setData(insertKey);
myhead.setLink(tail);
tail = myhead;
}
哦! 並且不要wordCounter
聲明為字段:將其聲明為局部變量 int 方法search
。 你總是可以在別處計算總和。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.