# 数据结构-简单栈的实现

79人阅读 评论(0)

简单的栈的实现，栈元素为类型为int，利用一个数组实现，使用时，构造栈有两种方式，一种为不指定栈的大小，

* Created by logaxy on 2017/1/3.
*/
public class MyStack {

private boolean actoIncrement = true;//栈是否自增长，当指定大小时为否
private static int INITIALSIZE = 4;//不指定栈大小时的初始化大小
private int array[];//栈以一个数组实现
private int top;

MyStack() {
array = new int[INITIALSIZE];
top = -1;
}

MyStack(int maxSize) {
actoIncrement=false;
if (maxSize < 0 || maxSize == 0)
throw new IllegalArgumentException();
array = new int[maxSize];
top = -1;
}

void push(int value) {
if (isFull()) {
if (actoIncrement) {
int[] temp = array;
array = new int[2 * array.length];
System.arraycopy(temp, 0, array, 0, temp.length);

} else {
throw new IndexOutOfBoundsException();
}
}

array[++top] = value;
}

int pop() {
if (isEmpty())
throw new IndexOutOfBoundsException();

return array[top--];
}

int peek() {
if (isEmpty())
throw new IndexOutOfBoundsException();

return array[top];
}

boolean isEmpty() {
return (top == -1);
}

boolean isFull() {
return !(top < array.length - 1);
}

public int getSize() {
return array.length;
}

}
测试程序：
public class Main {

public static void main(String[] args) {
testStack();
}

public static void testStack(){
MyStack myStack=new MyStack();
myStack.push(1);
myStack.push(2);
myStack.push(3);
myStack.push(4);
System.out.println("Top Is: "+myStack.peek());
System.out.println("Size IS:"+myStack.getSize());
System.out.println("Is Full: "+myStack.isFull());
myStack.push(5);
myStack.push(6);
System.out.println("Top Is: "+myStack.peek());
System.out.println("Size IS:"+myStack.getSize());
System.out.println("Is Full: "+myStack.isFull());
System.out.println(myStack.pop());
System.out.println(myStack.pop());
System.out.println(myStack.pop());
System.out.println(myStack.pop());
System.out.println(myStack.pop());
System.out.println(myStack.pop());
System.out.println("Is Empty:"+myStack.isEmpty());
System.out.println("Size IS:"+myStack.getSize());
}
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：4202次
• 积分：147
• 等级：
• 排名：千里之外
• 原创：12篇
• 转载：0篇
• 译文：0篇
• 评论：0条
阅读排行
评论排行