版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012292754/article/details/83315415
1 栈的实现
1.1 简单数组实现栈
package mystack;
public class ArrayStack {
private int top; //当前栈顶元素的下标
private int[] array;
public ArrayStack() {
array = new int[10];
top = -1;
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == array.length - 1;
}
public void push(int data) {
if (isFull()) System.out.println("Stack Overflow!!");
else {
array[++top] = data;
}
}
public int pop() {
if (isEmpty()) {
System.out.println("Stack is empty!!");
return 0;
} else {
return array[top--];
}
}
public void deleteStack() {
top = -1;
}
}
1.2 动态数组实现栈
package mystack;
public class DynArrayStack {
private int top;
private int capacity;
private int[] array;
public DynArrayStack(int capacity) {
this.capacity = capacity;
array = new int[capacity];
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == array.length - 1;
}
public void push(int data) {
if (isFull()) doubleStack();
array[++top] = data;
}
private void doubleStack() {
int newArray[] = new int[array.length * 2];
System.arraycopy(array, 0, newArray, 0, array.length);
array = newArray;
}
public int pop() {
if (isEmpty()) {
System.out.println("Stack Overflow!!!");
return -1;
}
else return array[top--];
}
public void deleteStack() {
top = -1;
}
}
1.3 链表实现栈
public class LLStack {
private LLNode headNode;
public LLStack(){
this.headNode = new LLNode(null);
}
public void Push(int data){
if(headNode==null) {
headNode = new LLNode(data);
}else if(headNode.getData() == null) {
headNode.setData(data);
}else{
LLNode llNode = new LLNode(data);
llNode.setNext(headNode);
headNode = llNode;
}
}
public int pop(){
if(headNode == null) return -1;
else{
int data = headNode.getData();
headNode = headNode.getNext();
return data;
}
}
public boolean isEmpty(){
if(headNode == null) return true;
else return fasle;
}
public void deleteStack(){
headNode = null;
}
}