java中的队(Queue)和栈(Stack)

  看着编程思想第四版,爽的是里面的程序,当你理解到这个程序的牛逼之处时,就是你拍板叫好的那一刻,终于连追带赶看到了第十一章持有对象,被这扫描版伤透了眼。写完这个笔记,眼保健操是个好主意。

【队和栈特点实验】

package com.jay.knowledge.queue_study;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * @function: Queue的学习(对列,对,就是队列)  典型的先进先出的容器(传送带似)
 * @author:Jay
 * @date:2013-12-5
 */
public class Queue001 {
	public static void main(String[] args) {
		//queue不支持ArrayList,如下会报错
		//Queue<String> queue = new ArrayList<String>();
		//queue支持LinkedList
		/*
		Queue<String> queue = new LinkedList<String>();
		queue.add("one");
		queue.add("two");
		queue.add("three");
		queue.add("four");
		queue.add("five");
		queue.add("six");
		
		Iterator<String> iterator = queue.iterator();
		while (iterator.hasNext()) {
			String q = (String) iterator.next();
			//先进先出
			System.out.print("   "+q);
		}*/
		
		Queue<String> queue = new LinkedList<String>();
		queue.offer("one");
		queue.offer("two");
		queue.offer("three");
		queue.offer("four");
		queue.offer("five");
		queue.offer("six");
		System.out.println("------进队顺序------------");
		System.out.println("one two three four five six");
		System.out.println("------出队顺序------------");
		//,poll删除并移动指针,peek()查询
		System.out.print("  "+queue.poll());
		System.out.print("  "+queue.poll());
		System.out.print("  "+queue.poll());
		System.out.print("  "+queue.poll());
		System.out.print("  "+queue.poll());
		System.out.print("  "+queue.poll());
		System.out.println();
		//比较先进后出的Stack
		Stack<String> stack = new Stack<String>();
		//进栈
		stack.push("one");
		stack.push("two");
		stack.push("three");
		stack.push("four");
		stack.push("five");
		stack.push("six");
		System.out.println("------进栈顺序------------");
		System.out.println("one two three four five six");
		System.out.println("------出栈顺序------------");
		//出栈pop删除并移动指针,peek()只拿出最后进栈的值
		System.out.print("  "+stack.pop());
		System.out.print("  "+stack.pop());
		System.out.print("  "+stack.pop());
		System.out.print("  "+stack.pop());
		System.out.print("  "+stack.pop());
		System.out.print("  "+stack.pop());
	}
}


【运行结果】

------进队顺序------------
one two three four five six
------出队顺序------------
  one  two  three  four  five  six
------进栈顺序------------
one two three four five six
------出栈顺序------------
  six  five  four  three  two  one
【方法说明】

1.栈(Stack):

①peek():只取出栈顶值,但不会对栈进行操作,如果不断去做操作,最后的得到的值是相同,此值是最后进去的值。

②push(T):向栈中添加值。

③pop():出栈,并操作栈,取出后进去的值,并删除,然后移动指针。

2.队列(Queue)

①peek():只取出队列中的值,不会对栈进行操作,如果不断去做操作,最后的得到的值是相同,此值是最先进去的值。

②offer(T):向队列中添加值。

③poll():出队列,并操作队列,取出先进队列的值,并删除,然后移动指针。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值