Day14
1. Background
今天是学习java的第十四天了,今天学习的是栈的基础知识。
主要是栈的结构以及删除和增加操作。
2. Description
2.1 Stack
我对栈的理解,就是一个像杯子容器,具有后进先出的特性。
数据只能从开口进来,从开口出去,而且,栈必须让上面的数据先出去后,下面额数据才能出去。
2.2 Push
这是往栈里面增加元素,这个操作的逻辑还是很好理解的。
先检查栈里面的元素满了没有,满了的话,就返回false,并说此栈已满。
如果栈中还有空位,则往其中加入给定数据,并把depth的数值加一。
2.3 Pop
往栈中删除元素则与增加元素同理,先检查栈是否为空,若为空,则返回false。
若不为空,则直接返回depth处的数据,并将depth减一即可。
3. Code
package datastructure;
public class CharStack {
/**
* The depth.
*/
public static final int MAX_DEPTH = 10;
/**
* The actual depth.
*/
int depth;
/**
* The data.
*/
char[] data;
/**
* Construct an empty char stack.
*/
public CharStack() {
depth = 0;
data = new char[MAX_DEPTH];
} // Of the first constructor
public String toString() {
String resultString = "";
for (int i = 0; i < depth; i++) {
resultString += data[i];
} // Of for i
return resultString;
} // Of toString
/**
*************
* Push an element.
* @param paraChar The given element.
* @return Success or not.
* ************
*/
public boolean Push(char paraChar) {
if (depth == MAX_DEPTH) {
System.out.println("Stack full");
return false;
}
data[depth] = paraChar;
depth++;
return true;
} // Of Push
/**
*************
* Pop an element.
* @return The poped char.
* ************
*/
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
/**
* The entrance of program.
*
* @param args Not used now.
*/
public static void main(String[] args) {
CharStack tempStack = new CharStack();
for (char i = 'a'; i < 'm'; i++) {
tempStack.Push(i);
System.out.println("The stack is: " + tempStack);
} // Of for i
char tempChar;
for (int i = 0; i < 12; i++) {
tempChar = tempStack.Pop();
System.out.println("Poped : " + tempChar);
System.out.println("The stack is: " + tempStack);
} // Of for i
} // Of main
} // Of CharStack
运行结果:











