/**
* 栈就是一组记录,表示形式先进后出
*
* 数组 链表 树 适应于数据库应用中做数据记录
* 栈和队列 1.通常情况作为程序员的工具来运用
* 2.受限访问
* 3.更加抽象(主要通过接口进行定义)
*
* 栈:数组表示
*/
class MyStack {
private int arr[] ;
private int maxSize;
private int top;
//初始化
public MyStack(int size){
maxSize = size;
arr = new int[maxSize];
top = -1;
}
//入栈
public void push(int value){
arr[++top] = value;//栈底是0下标
}
//出栈(查看并且删除)
public int pop(){
return arr[top--];
}
//查看
public int peek(){
return arr[top];
}
//判满
public boolean isFull(){
return top == maxSize - 1;
}
//判空
public boolean isEmpty(){
return top == -1;
}
public static void main(String[] args){
MyStack myStack = new MyStack(5);
if(!myStack.isFull()) myStack.push(55);
if(!myStack.isFull()) myStack.push(88);
if(!myStack.isFull()) myStack.push(99);
if(!myStack.isFull()) myStack.push(66);
if(!myStack.isFull()) myStack.push(22);
if(!myStack.isFull()) myStack.push(77);
if(!myStack.isFull()) myStack.push(44);
if(!myStack.isFull()) myStack.push(11);
while (!myStack.isEmpty()){
int value = myStack.pop();
System.out.print(value + " ");
}
System.out.println();
}
}
字符串反转:
/**
* 字符串反转
*/
class StringReverse {
private char arr[];
private int maxSize;
private int top;
public StringReverse(int size){
maxSize = size;
arr = new char[maxSize];
top = -1;
}
//入栈
public void push(char value){
arr[++top] = value;
}
//出栈
public char pop(){
return arr[top--];
}
//判空
public boolean isEmpty(){
return top == -1;
}
}
class Reverse{
//反转
public String doReverse(String str){
String output = "";
int size = str.length();
StringReverse stringReverse = new StringReverse(size);
for(int i=0;i<str.length();i++){
char in = str.charAt(i);
stringReverse.push(in);
}
while(!stringReverse.isEmpty()){
char c = stringReverse.pop();
output += c;
}
return output;
}
public static void main(String[] args){
String str = "qwert y";
Reverse reverse = new Reverse();
String value = reverse.doReverse(str);
System.out.println(value);
}
}