先来看下题目的要求
/**
* Returns true iff the list passed as argument contains at least
* the required number of consecutive occurrences of the object passed as argument.
* It returns false otherwise.
*
* @param number_to_find the number we are looking for in the list
* @param num_of_occs the minimum number of consecutive occurrences of element_to_find
* @param where_to_find the list where number_to_find is to be sought for
* @return true if the object is found consecutively the stated number of times
*/
也就是说给定一个list,一个数和一个连续次数,返回该数字是否在该list中连续出现了所给定的次数。
很简单,只是需要注意一下有关list的特性
PositionList<String> list = new NodePositionList<String>();
Position<String> cursor;
list.addFirst("vais"); // ["vais"]
list.addLast("a"); // ["vais", "a"]
list.addLast("aprobar"); // ["vais", "a", "aprobar"]
list.addFirst("no"); // ["no", "vais", "a", "aprobar"]
cursor = list.last();
list.set(cursor,"suspender"); // ["no", "vais", "a", "suspender"]
cursor = list.prev(cursor);
list.remove(cursor); // ["no", "vais", "suspender"]
cursor = list.prev(list.last());
list.set(cursor,"quiero"); // ["no", "quiero", "suspender"]
三个例子
public void show(PositionList<E> list) {
if (!list.isEmpty()) {
Position<E> cursor = list.first();
while (cursor != null) {
System.out.println(cursor.element());
if (cursor == list.last())
cursor = null;
else
cursor = list.next(cursor);
}
}
}
public void show(PositionList<E> list) {
if (!list.isEmpty()) {
Position<E> cursor = list.first();
while (cursor != null) {
System.out.println(cursor.element());
cursor = cursor == list.last() ? null : list.next(cursor);
}
}
}
public void show(PositionList<E> list) {
if (!list.isEmpty()) {
for (Position<E> cursor = list.first() ;
cursor != null ;
cursor = cursor == list.last() ? null : list.next(cursor) )
System.out.println(cursor.element());
}
}
}
附上此题代码
package n_Elements;
import net.datastructures.Position;
import net.datastructures.PositionList;
public class Check_consecutive_elements<E> {
public boolean n_elements(E element_to_find, int num_of_occs, PositionList<E> where_to_find){
int n=0;
//como practica 1
for (Position<E> cursor = where_to_find.first() ;
cursor != null && n<num_of_occs;
cursor = cursor == where_to_find.last() ? null : where_to_find.next(cursor) ){
if(element_to_find.equals(cursor.element()))
n++;
else
n=0;
}
return n==num_of_occs;
}
}