三.栈
栈只允许访问一个数据项:即最后插入的数据项。移除这个数据项后才能访问倒数第二个插入的数据项,以此类推。这种机制在不少编程环境中都很有用。
大部分微处理器运用基于栈的体系结构。当调用一个方法时,把它的返回地址和参数压入栈,当方法结束返回时,那些数据出栈。栈操作就是嵌入在微处理器中。
以下代码是最基本的栈数据结构的java实现,之后还会有更多关于栈的其它应用,每个数据和方法都有注释说明。
- package Stack;
- //stack.java
- //demostrates stacks
- //
- public class stack
- {
- private int maxSize; //size of stack array
- private long[] stackArray;
- private int top; //top of the stack
- //........................................................
- public stack(int s) //constructor
- {
- maxSize=s; //set array size
- stackArray=new long [maxSize];//create array
- top=-1; //no item yet
- }
- //........................................................
- public void push(long j) //put item on top of stack
- {
- stackArray[++top]=j; //increment too,insert item
- }
- //........................................................
- public long pop() //take item from top of stack
- {
- return stackArray[top--];
- }
- //........................................................
- public long peek() //peek the top of stack
- {
- return stackArray[top];
- }
- //........................................................
- public boolean isEmpty() //true if stack is empty
- {
- return(top==-1);
- }
- //........................................................
- public boolean isFull() //true if stack is full
- {
- return(top==maxSize-1);
- }
- //........................................................
- } //end class stack
类的实例化调用:
- package Stack;
- public class stackApps {
- /**
- * @param args
- */
- public static void main(String[] args)
- {
- // TODO Auto-generated method stub
- stack theStack=new stack(10);//make the new stack
- theStack.push(20); //push items onto stack
- theStack.push(40);
- theStack.push(60);
- theStack.push(80);
- while(!theStack.isEmpty()) //until it's empty
- {
- long value=theStack.pop();//delete item from stack
- System.out.print(value);
- System.out.print (" ");
- }//end while
- System.out.println();
- }//end main
- }//end stackApps
3.运行结果
- 80 60 40 20