一个Peek实现

当我们要parse什么东西的时候,常常会需要对自己的character stream或者token list实现一个Peek 函数。之前偶的实现都是多读一位,有的时候还要记一个偏移量。用来保证peek以后read不会受影响。最近看到一个Peek实现,很简单,很方便,不知道大家都是已经这样实现的。

主要思想就是添加一个cached value.

private   char  cachedChar;

public   char  Peek()
{
    
if (cachedChar  ==   null )
    {
        cachedChar 
=  RealRead();
    }
    
return  cachedChar;
}

public   char  Read()
{
    
char  ret;
    
if (cachedChar  !=   null )
    {
        ret 
=  cachedChar;
        cachedChar 
=   null ;
    }
else
    {
        ret 
=  RealRead();
    }
    
    
return  ret;
}

private   char  RealRead()
{
    
//  your implementation
}

希望对你有帮助

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
队列(Queue)是一种先进先出(First In First Out,FIFO)的数据结构,其中最先进入的元素会被最先处理。在Java中,我们可以通过自己实现一个队列来更好地理解它的内部原理。 Java中的队列可以使用数组或链表来实现,这里我们选择链表实现队列。首先,我们定义一个Node类: class Node { int data; Node next; public Node(int data) { this.data = data; this.next = null; } } 其中,data表示结点存储的数据,next表示链表中下一个结点的引用。 然后,我们定义一个Queue类,并定义一些基本操作方法: class Queue { Node head; Node tail; int size; public Queue() { this.head = null; this.tail = null; this.size = 0; } public boolean isEmpty() { return head == null; } public int size() { return size; } public int peek() { if (isEmpty()) { throw new NoSuchElementException("Queue is empty"); } return head.data; } public void add(int data) { Node newNode = new Node(data); if (tail != null) { tail.next = newNode; } tail = newNode; if (head == null) { head = newNode; } size++; } public int remove() { if (isEmpty()) { throw new NoSuchElementException("Queue is empty"); } int data = head.data; head = head.next; if (head == null) { tail = null; } size--; return data; } } 在队列中,head表示队首,tail表示队尾。size表示队列中元素的数量。isEmpty方法用于判断队列是否为空;size方法用于获取队列中元素的数量;peek方法用于返回队首元素的值,但不删除;add方法用于向队列中添加元素;remove方法用于删除队首元素,并返回其值。 在实现完毕Queue类后,我们可以使用以下代码来测试它: Queue q = new Queue(); q.add(1); q.add(2); q.add(3); System.out.println(q.peek()); // 输出1 System.out.println(q.size()); // 输出3 System.out.println(q.remove()); // 输出1 System.out.println(q.peek()); // 输出2 System.out.println(q.size()); // 输出2 以上就是一个简单的Java队列的实现方法。通过实现一个队列,我们可以更好地理解队列的原理,进而更好地应用于实际开发中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值