java实现栈详解程序员

/** 
 * Created by murphy on 2016/7/4. 
 */ 
public class Stack { 
    private int DEFAULT_SIZE=12; 
    private int[] arr; 
    private int count=0; 
 
    public Stack(int size){ 
        arr=new int[size]; 
    } 
    public Stack(){ 
        arr=new int[DEFAULT_SIZE]; 
    } 
 
    public void push(int val){ 
        arr[count++]=val; 
    } 
    public int pop(){ 
        int temp=arr[count-1]; 
        count--; 
        return temp; 
    } 
    public int peek(){ 
        return arr[count-1]; 
    } 
    public int size(){ 
        return count; 
    } 
 
    public boolean isEmpty(){ 
        return count == 0; 
    } 
    public static void main(String[] args){ 
        Stack stack = new Stack(); 
        stack.push(10); 
 
        stack.push(20); 
 
        stack.push(30); 
 
        System.out.println(stack.peek()); 
        System.out.println(stack.pop()); 
        System.out.println(stack.pop()); 
        System.out.println(stack.size()); 
        System.out.println(stack.isEmpty()); 
        System.out.println(stack.pop()); 
        System.out.println(stack.isEmpty()); 
    } 
} 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/7197.html

(0)
上一篇 2021年7月17日
下一篇 2021年7月17日

相关推荐

发表回复

登录后才能评论