一道简单的有关链表的练习

先来看下题目的要求

	/**
	 * 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;
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值