java中队列和栈的使用

package com.ipmotor.sm.db;

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

/**
 * 测试jdk中的栈和队列
 * @author scott
 *
 */
public class TestQueueAndStack {
    
    /**
     * 测试队列
     * <pre>
     * 队列特点,先进先出,后进后出,火车过山洞例子
     * </pre>
     */
    static void testQueue(){
        Queue<String> queue=new LinkedList<String>();
        //添加几个元素
        queue.offer("a");
        queue.offer("b");
        queue.offer("c");
        queue.offer("d");
        queue.offer("e");
        queue.add("1");
        queue.add("2");
        queue.add("3");
        queue.add("4");
        queue.add("5");
        System.out.println("队列中的元素是:"+queue);
        //弹出元素
        queue.poll();
        System.out.println("队列中的元素是:"+queue);
        //查看队列中首个元素,并不移除
        String peek=queue.peek();
        System.out.println("查看队列中首个元素,并不移除:"+peek);
        System.out.println("队列中的元素是:"+queue);
    }
    
    
    /**
     * 测试栈
     * <pre>
     * 先进后出,后进先出,水桶倒水
     * </pre>
     */
    static void testStack(){
        Stack<String> stack=new Stack<String>();
        //添加几个元素
        stack.push("a");
        stack.push("b");
        stack.push("c");
        stack.push("d");
        stack.push("e");
        stack.add("1");
        stack.add("2");
        stack.add("3");
        stack.add("4");
        stack.add("5");
        System.out.println("栈中的元素是:"+stack);
        //弹出元素
        stack.pop();
        System.out.println("栈中的元素是:"+stack);
        //查看栈中首个元素,并不移除
        String peek=stack.peek();
        System.out.println("查看栈中首个元素,并不移除:"+peek);
        System.out.println("栈中的元素是:"+stack);
    }
    

    /**
     * @param args
     */
    public static void main(String[] args) {
        testQueue();
        System.out.println("-------栈--------");
        testStack();
    }

}

队列中的元素是:[a, b, c, d, e, 1, 2, 3, 4, 5]
队列中的元素是:[b, c, d, e, 1, 2, 3, 4, 5]
查看队列中首个元素,并不移除:b
队列中的元素是:[b, c, d, e, 1, 2, 3, 4, 5]
-------栈--------
栈中的元素是:[a, b, c, d, e, 1, 2, 3, 4, 5]
栈中的元素是:[a, b, c, d, e, 1, 2, 3, 4]
查看栈中首个元素,并不移除:4
栈中的元素是:[a, b, c, d, e, 1, 2, 3, 4]
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值