栈的基本概念:
栈(stack)是仅限定在表尾进行插入和删除操作的线性表。栈就是一个线性表,只不过,栈的Insert 和 delete只能在表尾。普通的线性表,在表中的任意位置都可以进行insert和delete操作。后进先出,先进后出。
栈顶(Top): 进行插入和删除操作的一端。
栈底(Bottom)
栈的基本操作:
(1)初始化一个栈:InitStack
(2)销毁一个栈:DestroyStack
(3)清空一个栈:ClearStack
(4)判断一个栈是否为空:StackIsEmpty
(5)返回栈中元素个数,即栈的长度:StackLength
(6)入栈,把一个元素加入到栈中:Push
(7)出栈,把栈顶元素给干掉:Pop
(8)返回栈顶元素,但不出栈:GetTop
下面介绍两种最基本的操作:进栈与出栈
package day_14;
public class day14 {
public static final int MAX_DEPTH = 10;
int depth;
char[] data;
public day14() {
depth = 0;
data = new char[MAX_DEPTH];
}
public String toString() {
String resultString = "";
for (int i = 0; i < depth; i++) {
resultString += data[i];
}
return resultString;
}
//入栈
public boolean push(char paraChar) {
if (depth == MAX_DEPTH) {
System.out.println("Stack full.");
return false;
} // Of if
data[depth] = paraChar;
depth++;
return true;
}// Of push
//出栈
public char pop() {
if (depth == 0) {
System.out.println("Nothing to pop.");
return '\0';
} // Of if
char resultChar = data[depth - 1];
depth--;
return resultChar;
}// Of pop
public static void main(String args[]) {
day14 tempStack = new day14();
for (char ch = 'a'; ch < 'm'; ch++) {
tempStack.push(ch);
System.out.println("The current stack is: " + tempStack);
}
char tempChar;
for (int i = 0; i < 12; i++) {
tempChar = tempStack.pop();
System.out.println("Poped: " + tempChar);
System.out.println("The current stack is: " + tempStack);
}
}
}
结果为: