# 用java数组实现栈

1942人阅读 评论(0)

talk is cheap, show me the code

package leilei.bit.edu.stacktest;

/**
* @author lei.wang
*
*/

public class Stack {

//存数据的数组
int[] data;

//栈的最大长度
private int size;
//栈顶的位置
private int top;

public Stack(int size) {
this.size = size;
data = new int[size];
top = -1;
}

public int getSize() {
return size;
}

public int getTop() {
}

/**
* 判断是否为空栈
* @return
*/
public boolean isEmpty()     {
}

/**
* 判断是否为满栈
* @return
*/
public boolean isFull() {
return (top+1) == size;
}

/**
* 压栈操作
* @param data
* @return
*/
public boolean push(int data) {
if(isFull()) {
System.out.println("the stack is full!");
return false;
} else {
top++;
this.data[top] = data;
return true;
}
}

/**
*  弹栈操作
* @return
* @throws Exception
*/
public int pop() throws Exception {
if(isEmpty()) {
throw new Exception("the stack is empty!");
} else {
return this.data[top--];
}
}

/**
* 获取栈顶的元素,但不弹栈
* @return
*/
public int peek() {
return this.data[getTop()];
}

public static void main(String[] args) {
Stack stack = new Stack(20);
stack.push(0);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("Now the top_num is:" + stack.peek());

while(! stack.isEmpty()) {
try {
System.out.println(stack.pop());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}


Now the top_num is:3
3
2
1
0

个人资料
等级：
访问量： 161万+
积分： 1万+
排名： 1050
最新评论