`

Stack的使用方法

    博客分类:
  • java
阅读更多

import java.util.Stack;

public class StackTest {

	static String months[] = {"zhang","gua","shi","ge","hao","ren"};
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void main(String args[]){
		Stack stk = new Stack();      //栈的声明
		for(int i=0;i<months.length;i++){
			stk.push(months[i]);      //入栈
		}
		System.out.println("stk = "+stk);  //stk = [zhang, gua, shi, ge, hao, ren]
		stk.addElement("the last line");   //插入的另一种形式
		System.out.println("stk = "+stk);  //stk = [zhang, gua, shi, ge, hao, ren, the last line]
		System.out.println("element 5 = "+stk.elementAt(5-1)); //下标是从0开始的
		System.out.println("popping elements:");
		while(!stk.empty()){
			System.out.println(stk.pop());  //出栈
		}
	}
	
}
// Stack 只是 Vector 的一种形式,所有Vector的方法都可以在Stack上使用

//************************************************************************
import java.util.*;

public class StackTest_1 {

	static void Enterpush(Stack<String> st, String str) { // 入栈方法 {
		st.push(str);// 调用Stack的push方法
		System.out.println("入栈 ->");
		System.out.println(str);
		System.out.println("Stack: " + st);
	}

	static void Outpop(Stack<String> st) {// 出栈方法
		System.out.print("出栈 -> ");
		String ss = st.pop().toString();// 调用Stack的pop方法
		System.out.println(ss);
		System.out.println("Stack: " + st);
	}
	
	public static void main(String[] args) {
		Stack<String> st = new Stack<String>();// 创建Stack对象
		System.out.println("Stack: " + st);
		for (int i = 0; i < 5; i++) {
			Enterpush(st, (i + 1) + "");// 利用for循环进行入栈操作,由于第二个参数的数据类型是String,可以通过+"",将int转换成String
		}
		for (int i = 0; i < 10; i++) {
			if (st.empty()) {// 判断栈是否为空,如果为空则返回true
				System.out.println("栈中内容已为空,不能在进行出栈操作");
				break; // 提前结束循环
			} else {
				Outpop(st);// 调用自定义的出栈操作
			}
		}
	}

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics