Java学习之路(7)----数据结构(栈)

文章目录


帮助理解栈

//栈的学习
import java.util.*;
public class StackTest{
	
	static void showPush(Stack<Integer> st,Integer v){
		
		st.push(v);
		System.out.println("push("+v+")");
		System.out.println("Stack:"+st);
			
	}
	
	static void showPush2(Stack<Integer> st,int v){
		
		st.push(new Integer(v));
		System.out.println("push("+v+")");
		System.out.println("Stack:"+st);
		
		
	}
	
	static void showPop(Stack<Integer> st){
		
		System.out.println("pop->");
		//Integer v = new Integer();//语法错误
		Integer v = st.pop();
		System.out.println(v);
		System.out.println(st);
	}
	
	
	public static void main(String[] args){
		
		Stack<Integer> st = new Stack<Integer>();
		
		showPush(st,25);
		showPush(st,25);
		showPush2(st,25);
		showPush2(st,20);
		System.out.println(st.search(20));//查找对象出现的第一个的位置,栈顶为1
		System.out.println(st.peek());//查看栈顶对象
		showPop(st);
		showPop(st);
		showPop(st);
		System.out.println(st.empty());
		
		try{
			showPop(st);
		System.out.println(st.empty());
		showPop(st);
			
		}catch(EmptyStackException e){
			System.out.println("empty");
			
		}
		
		
	}
}
发布了12 篇原创文章 · 获赞 1 · 访问量 121

猜你喜欢

转载自blog.csdn.net/weixin_43351473/article/details/104372638