环形对列(circle queue 1329 P103)

本文介绍如何使用环形链表实现队列,并详细解释了入列和出列的操作流程。通过具体代码展示了如何在只有最后一个节点的情况下,进行元素的添加和移除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

描述:使用链表(LinkedList) 实现一个对列。给出最后一个Node ;

思路:
1.环形链表的实现方式:最后一个节点的next指向第一个节点。
2.入列方式:将最后一个节点last指向新的节点,
                    并将新的节点node的next指向last.next(原节点last的next, 这里为首节点). 
                    最后把新节点node定义为最后一个节点last.
3.出列方式:找到最后一个节点的next,也就是首节点,first = last.next
                    然后将last.next 指向 first.next;跳过首节点first,定义首节点first.next为新的首节点。
                    输出 first.item
注意:不能直接输出 last.next.item;因为只有一个节点的这种情况会导致last 为空,输出的item也必然为空的情况!

思路草图:


代码如下:
package chapter1.a3 ;

/**
* Created by fengjw on 2017/8/13
* Code Change The World!
*/

public class Example1329< Item> { //circle queue

private Node last ;

private class Node{
Item item ;
Node next ;

public Node( Item item){
this. item = item ;
}
}

/**
* enqueue operation
*/
public void enqueue( Item item){
Node node = new Node(item) ;
if ( last == null){
last = node ;
last. next = last ;
} else { //cycle
Node origin = last. next ;
last. next = node ;
node. next = origin ; // origin is the first Node

last = node ; // by the 'last' point to the last Node
}
}

/**
* dequeue operation
*/
public Item dequeue(){
if ( last == null){
throw new NullPointerException( "queue is empty!") ;
}
Node first = last. next ;

if (first == last){
last = null; // '@Important'
} else {
last. next = first. next ;
}
return first. item ; // or last.next.item? Error!
// Because : if LinkedList only have one Node,
//'last = null'; return last.next is mean return null; not get the item.
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值