数组实现栈(Java)

来源:互联网 发布:美国博士申请 知乎 编辑:程序博客网 时间:2024/05/16 10:12

1.1.  栈的数据结构

栈是一种先进后出的数据结果,只能在一端(称为栈顶(top))对数据项进行插入和删除。

1.2.  Java实现

StackTest

[java] view plain copy
print?
  1. package ch04;  
  2.    
  3. public class StackTest {  
  4.    
  5.     public static void main(String[] args) {  
  6.    
  7.        ArrayStack stack = new ArrayStack(10);  
  8.        System.out.println("isEmpty: "+stack.isEmpty());  
  9.        for(int i = 0;i<10;i++){  
  10.            stack.push(i);  
  11.        }  
  12.        System.out.println("isFull: "+stack.isFull());  
  13.         
  14.        while(!stack.isEmpty()){  
  15.            System.out.println(stack.pop());  
  16.        }  
  17.         
  18.     }  
  19.    
  20. }  
  21.    
  22. class ArrayStack{  
  23.     private int[] arrInt;//内置数组  
  24.     private int top;//栈顶指针  
  25.      
  26.     public ArrayStack(int size){  
  27.        this.arrInt = new int[size];  
  28.        top = -1;  
  29.     }  
  30.      
  31.     /** 
  32.      * 判断栈是否为空 
  33.      * @return 
  34.      */  
  35.     public boolean isEmpty(){  
  36.        return -1 == top;  
  37.     }  
  38.      
  39.     /** 
  40.      * 判断栈是否已满 
  41.      * @return 
  42.      */  
  43.     public boolean isFull(){  
  44.        return arrInt.length -1 == top;  
  45.     }  
  46.     /** 
  47.      * 向栈顶插入一个元素 
  48.      * @param item 
  49.      */  
  50.     public void push(int item){  
  51.        if(isFull()){  
  52.            throw new RuntimeException("栈已满");  
  53.        }  
  54.        arrInt[++top] = item;  
  55.     }  
  56.      
  57.     /** 
  58.      * 从栈顶取出一个元素 
  59.      * @return 
  60.      */  
  61.     public int pop(){  
  62.        if(isEmpty()){  
  63.            throw new RuntimeException("栈为空");  
  64.        }  
  65.        return arrInt[top--];  
  66.     }  
  67. }  

 

结果如下:

isEmpty: true

isFull: true

9

8

7

6

5

4

3

2

1

0

 

原创粉丝点击