首页 > 其他 > 详细

堆栈 先进后出的使用案例

时间:2017-01-18 10:51:44      阅读:223      评论:0      收藏:0      [点我收藏+]

案例出自于:java编程参考官方教程   130页

 

package com.chinadays.learn;

public class Stack {

	private int stack[] = new int[10];

	int tos;

	public Stack() {
		super();
		this.tos = -1;
	}

	void push(int item) {
		if (item >= 9)
			System.out.println("Stack is full!");

		else
			stack[++tos] = item;
	}

	int pop() {
		if (tos < 0) {
			System.out.println("Stack underflow");
			return 0;
		} else
			return stack[tos--];
	}

}

  

 

使用方法:

 

package com.chinadays.learn;

public class TestStack {
    public static void main(String[] args) {
        Stack st1 = new Stack();

        Stack st2 = new Stack();

        for (int i = 0; i < 10; i++)
            st1.push(i);

        for (int i = 0; i < 20; i++)
            st2.push(i);

        for (int i = 0; i < 10; i++)
            System.out.println(st1.pop());

        for (int i = 0; i < 20; i++)
            System.out.println(st2.pop());

    }
}

 

 

 

运行结果:

 

Stack is full!
Stack is full!
Stack is full!
Stack is full!
Stack is full!
Stack is full!
Stack is full!
Stack is full!
Stack is full!
Stack is full!
Stack is full!
Stack is full!
8
7
6
5
4
3
2
1
0
Stack underflow
0
8
7
6
5
4
3
2
1
0
Stack underflow
0
Stack underflow
0
Stack underflow
0
Stack underflow
0
Stack underflow
0
Stack underflow
0
Stack underflow
0
Stack underflow
0
Stack underflow
0
Stack underflow
0
Stack underflow
0

堆栈 先进后出的使用案例

原文:http://www.cnblogs.com/anpajin/p/6295710.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!