一.栈的元素
一个数组:用来储存数据,数组有个长度就是栈的容量。
一个标志位:栈顶top,这也是栈目前的容量。
二.栈的操作
非常简单,入栈和出栈。下面给出测试。
package datastructure.list;
/**
****************************
* TODO 这里使用字符站后面还有题
*
* @author Chen Fan
* @version 1.0 time 2021年12月22日
****************************
*/
public class CharStack {
/**
* The depth.
*/
public static final int MAX_DEPTH = 10;
/**
* The actual depth
*/
int depth;
// 数据用一个数组来装
char[] data;
/**
* ******************** 初始化栈
*********************
*/
public CharStack() {
depth = 0;
data = new char[MAX_DEPTH];
}// Of the first constructor
/**
*
*********************
* TODO Overrides the methd claimed in Object, the superclass of class.
*
* @return String
*********************
*/
public String toString() {
String resultString = "";
for (int i = 0; i < depth; i++) {
resultString += data[i];
} // Of for i
return resultString;
}// Of toString
/**
*
*********************
* TODO Push an element
*
* @param paraChar
* @return The result is true or false.
*********************
*/
public boolean push(char paraChar) {
if (depth == MAX_DEPTH) {
System.out.println("Stack is full.");
return false;
} // Of if
data[depth] = paraChar;
depth++;
return true;
}
/**
*
*********************
* TODO Pop an element
*
* @return The top of the element , if no element return ' '
*********************
*/
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[]) {
// 创建一个栈的引用并且指向新值
CharStack tempStack = new CharStack();
for (char ch = 'a'; ch < 'm'; ch++) {
tempStack.push(ch);
System.out.println("The current stack is: " + tempStack);
} // Of for ch
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);
} // Of for i
}// Of main
}