public class QueueAndStack {
private static final long LEVEL = 20150701;//码讲版本
/**
* 队列的基本操作
*/
public void testQueue() {
Queue<String> queue = new LinkedList<String>();
System.out.println("向队尾添加元素:"+queue.offer("one"));
queue.offer("two");
queue.offer("three");
queue.offer("four");
System.out.println("全部队列:" + queue);
System.out.println("出队操作:" + queue.poll());
System.out.println("取出后全部队列:" + queue);
System.out.println("查询队尾元素,不出队:"+queue.peek());
System.out.println("查询后全部队列:" + queue);
System.out.println("当前队列元素个数:"+queue.size());
//队列的遍历 while方式并做出队操作
while(queue.size()>0){
System.out.println("遍历:"+queue.poll());
}
System.out.println("While遍历后队列:"+queue);
//迭代器遍历,不会做出队操作
System.out.println("向队尾添加元素:"+queue.offer("one"));
queue.offer("two");
queue.offer("three");
queue.offer("four");
for(String q:queue){
System.out.println("遍历:"+q);
}
System.out.println("迭代遍历后队列:"+queue);
}
/**
* 栈的基本操作
*/
@Test
public void testStack(){
Deque<String> stack = new LinkedList<String>();
stack.push("one");
stack.push("two");
stack.push("three");
stack.push("four");
System.out.println("查看栈顶元素:"+stack.peek());
System.out.println("出栈:"+stack.pop());
System.out.println("查看栈顶元素:"+stack.peek());
System.out.println("栈大小:"+stack.size());
//迭代遍历
for(String q:stack){
System.out.println("遍历:"+q);
}
System.out.println("迭代遍历后队列:"+stack);
//出栈遍历
while(stack.size()>0){
System.out.println("出栈遍历:"+stack.pop());
}
System.out.println("栈大小:"+stack.size());
}
}
【Java】栈和队列
最新推荐文章于 2015-11-01 15:54:55 发布