栈:
栈是一种后进先出的线性表数据结构,分为栈顶和栈底两端,仅允许在表的一端插入元素,这一端被称为栈顶,另外一端称之为栈底。栈,只有两种操作,分为入栈(压栈)和出栈(退栈);向栈中添加元素的操作叫做入栈,相反从栈中删除元素叫做出栈。
栈(stack),是一种线性存储结构,它有以下几个特点:
- 栈中数据是按照"后进先出"方式进出栈的。
- 向栈中添加/删除数据时,只能从栈顶进行操作。
栈通常包括的三种操作:push、peek、pop。
-
push – 向栈中添加元素。
-
peek – 返回栈顶元素。
-
pop – 返回并删除栈顶元素的操作。
图示如下(图片来源网路,侵删)
栈的基本操作(详细代码)
/**
* 栈的基本操作
*
* @author 晨曦
*
*/
public class MyStack {
private int Size;// 栈的大小
private char[] arr;
private int top;// 指向栈顶元素
public MyStack(int size) {
this.Size = size;
this.arr = new char[Size];
this.top = -1;
}
/**
* 压入数据
*
* @param value
*/
public void push(char value) {
arr[++top] = value;
}
/**
* 返回栈顶元素
* @return
*/
public char peek() {
return arr[top];
}
/**
* 出栈
*
* @return
*/
public char pop() {
if (isEmpty())
throw new NullPointerException("此栈为空!!");
return arr[top--];
}
/**
* 查看压入的栈的结果
*
*/
public void print() {
if (isEmpty()) {
System.out.printf("此栈为空!!!");
}
System.out.printf("栈的大小为:%d\n", Size);
int i = Size - 1;
while (i >= 0) {
System.out.print(arr[i]);
i--;
}
}
/**
* 判断栈是否为空
*
* @return
*/
public boolean isEmpty() {
return (top == -1);
}
/**
* 判断栈是否已满
*
* @return
*/
public boolean isFull() {
return (top == Size - 1);
}
}
接下来我们new一个测试类,调用上面的基本操作方法
public static void main(String[] args) {
MyStack stack = new MyStack(30);
stack.push('菜');
stack.push('徐');
stack.push('坤');
stack.push(',');
stack.push('鸡');
stack.push('你');
stack.push('太');
stack.push('美');
stack.push('!');
stack.push(' ');
stack.push('坤');
stack.push('徐');
stack.push('菜');
stack.push('!');
stack.push('美');
stack.push('太');
stack.push('你');
stack.push('鸡');
System.out.println("栈顶元素:");
System.out.println(stack.peek());
System.out.println("进栈结果:");
stack.print();
System.out.println(" ");
System.out.println("出栈结果:");
while (!stack.isEmpty()) {
System.out.print(stack.pop());
}
}