package java11to20;
public class D14_CharStack {
public static final int Max = 25;
int depth = 0;
char[] data;
public static void main(String[] args) {
// TODO Auto-generated method stub
D14_CharStack Stack = new D14_CharStack();
for (char chData = 'a'; chData <= 'z'; chData++) {
Stack.push(chData);// 入栈
System.out.println(String.format("栈中现有值:%s", Stack));
}
char charData;
for (int i = 0; i < 26; i++) {
charData = Stack.pop();// 出栈
System.out.println("出栈值: " + charData);
System.out.println("栈中现有值: " + Stack);
}
}
public D14_CharStack() {
depth = 0;
data = new char[Max];
}
public String toString() {
String result = "";
for (int i = 0; i < depth; i++) {
result += data[i];
}
return result;
}
public boolean push(char paraChar) {
if (depth == Max) {
System.out.println("栈满");
return false;
}
data[depth] = paraChar;
depth++;
return true;
}
public char pop() {
if (depth == 0) {
System.out.println("栈空");
return '\0';
}
char result = data[depth - 1];
depth--;
return result;
}
}
输出结果:
栈中现有值:a
栈中现有值:ab
栈中现有值:abc
栈中现有值:abcd
栈中现有值:abcde
栈中现有值:abcdef
栈中现有值:abcdefg
栈中现有值:abcdefgh
栈中现有值:abcdefghi
栈中现有值:abcdefghij
栈中现有值:abcdefghijk
栈中现有值:abcdefghijkl
栈中现有值:abcdefghijklm
栈中现有值:abcdefghijklmn
栈中现有值:abcdefghijklmno
栈中现有值:abcdefghijklmnop
栈中现有值:abcdefghijklmnopq
栈中现有值:abcdefghijklmnopqr
栈中现有值:abcdefghijklmnopqrs
栈中现有值:abcdefghijklmnopqrst
栈中现有值:abcdefghijklmnopqrstu
栈中现有值:abcdefghijklmnopqrstuv
栈中现有值:abcdefghijklmnopqrstuvw
栈中现有值:abcdefghijklmnopqrstuvwx
栈中现有值:abcdefghijklmnopqrstuvwxy
栈满
栈中现有值:abcdefghijklmnopqrstuvwxy
出栈值: y
栈中现有值: abcdefghijklmnopqrstuvwx
出栈值: x
栈中现有值: abcdefghijklmnopqrstuvw
出栈值: w
栈中现有值: abcdefghijklmnopqrstuv
出栈值: v
栈中现有值: abcdefghijklmnopqrstu
出栈值: u
栈中现有值: abcdefghijklmnopqrst
出栈值: t
栈中现有值: abcdefghijklmnopqrs
出栈值: s
栈中现有值: abcdefghijklmnopqr
出栈值: r
栈中现有值: abcdefghijklmnopq
出栈值: q
栈中现有值: abcdefghijklmnop
出栈值: p
栈中现有值: abcdefghijklmno
出栈值: o
栈中现有值: abcdefghijklmn
出栈值: n
栈中现有值: abcdefghijklm
出栈值: m
栈中现有值: abcdefghijkl
出栈值: l
栈中现有值: abcdefghijk
出栈值: k
栈中现有值: abcdefghij
出栈值: j
栈中现有值: abcdefghi
出栈值: i
栈中现有值: abcdefgh
出栈值: h
栈中现有值: abcdefg
出栈值: g
栈中现有值: abcdef
出栈值: f
栈中现有值: abcde
出栈值: e
栈中现有值: abcd
出栈值: d
栈中现有值: abc
出栈值: c
栈中现有值: ab
出栈值: b
栈中现有值: a
出栈值: a
栈中现有值:
栈空
出栈值: