编辑:解决了.显然,返回0工作!
好吧,这么长的故事,我必须返回一个int值,但是当链接列表为空时没有.我该怎么做?
public int countDuplicates() {
int duplicates = 0;
ListNode current = front;
int num = current.data;
current = current.next;
while(current != null) {
if(current.data == num) {
duplicates++;
} else {
num = current.data;
}
current = current.next;
}
return duplicates;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试这个:
if(front == null) {
return ;
}
Run Code Online (Sandbox Code Playgroud)
这不起作用.我能做什么?
好的,这就是我要做的事情:
将传递的内容拆分List为单独的行,然后使用分隔符拆分这些行,然后将这些部分添加到a Map.
我的代码:
public GrammarSolver(List<String> rules) {
if(rules == null || rules.size() == 0) {
throw new IllegalArgumentException();
}
Map<String, String> rulesMap = new HashMap<String, String>();
Iterator<String> i = rules.iterator();
while(i.hasNext()) {
String rule = i.next(); // store a line from 'rules' List
String[] parts = rule.split("::="); // split the line into non-terminal and terminal
rulesMap.put(parts[0], parts[1]); // Put the two parts into the map
}
// TODO: exception when duplicate key in map
}
Run Code Online (Sandbox Code Playgroud)
一切正常,但现在我的任务说如果任何行的键重复(发生多次),我需要抛出异常. …