package com.fengling.test;
/**
* 数组实现栈
*/
public class StackTest {
private char[] stack;
private int maxSize; //栈的大小
private int top;
public StackTest(int size) {
maxSize = size;
top = -1;
stack = new char[maxSize];
}
/**
* 入栈
*/
public void push(char value) {
stack[++top] = value;
}
/**
* 出栈
*/
public char pop() {
return stack[top--];
}
/**
* 访问栈顶元素
*/
public char peek() {
return stack[top];
}
/**
* 判断栈满
*/
public boolean isFull() {
return maxSize - 1 == top;
}
/**
* 判断栈空
*/
public boolean isEmpty() {
return top == -1;
}
/**
* 倒序输出
*/
public static void main(String[] args) {
String s = "风灵";
StackTest st = new StackTest(s.length());
for(int i = 0; i < s.length(); i++){
st.push(s.charAt(i));
}
while(!st.isEmpty()){
System.out.println(st.pop());
}
}
}
package com.fengling.test;
import java.util.LinkedList;
/**
* 链表实现栈
*/
public class StackTest {
private LinkedList<Object> a = new LinkedList<>();
/**
* 入栈
*/
public void push(char value){
a.addFirst(value);
}
/**
* 出栈
*/
public Object pop(){
return a.removeFirst();
}
/**
* 访问栈顶元素
*/
public Object peek(){
return a.getFirst();
}
/**
* 判断栈空
*/
public boolean isEmpty(){
return a.isEmpty();
}
/**
* 倒序输出
*/
public static void main(String[] args) {
StackTest st = new StackTest();
String s = "风灵";
for(int i = 0; i < s.length(); i++) {
st.push(s.charAt(i));
}
while (!st.isEmpty()){
System.out.println(st.pop());
}
}
}