简介:
栈也是数据结构中的一种,类似于顺序表和链表,最大的区别就是数据的存储操作。对于栈而言,把允许操作的一端叫做栈顶,只允许对栈顶进行插入和删除,把不可操作的一端称为栈底,它是一种先进后出或后进先出的顺序表。
Java实现的代码
入栈:
//入栈操作
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 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
/*
* Overrides the method claimed in object, the superclass of any class.
*/
public String toString() {
String resultString = "";
for (int i = 0; i < depth; i++) {
resultString += data[i];
} // of for i
return resultString;
}// of toString
// 入栈操作
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[]) {
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
}// of charStack