什么是栈?
- 栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则。
- 压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。
- 出栈:栈的删除操作叫做出栈。出数据在栈顶。
栈的实现
- 这里用顺序表来实现
public class MyStack {
private int[] array = new int[100];
private int size = 0;
public void push(int v) {
array[size++] = v;
}
public int pop() {
return array[--size];
}
public int peek() {
return array[size - 1];
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
}
- 用链表来实现
public class MyStack {
Node cur;
class Node{
private int val;
private Node next;
public Node(int val) {
this.val = val;
}
}
public void push(int v){
Node node = new Node(v);
if(this.cur == null){
this.cur = node;
}
node.next = this.cur;
this.cur = node;
}
public int pop() {
if(isEmpty()){
throw new RuntimeException("栈为空!");
}
int data = this.cur.val;
this.cur = cur.next;
return data;
}
public int peek() {
if(isEmpty()){
throw new RuntimeException("栈为空!");
}
return this.cur.val;
}
public boolean isEmpty() {
return this.cur == null;
}
public int size() {
int size = 0;
Node head = this.cur;
if(head == null){
return size;
}
while(head != null){
size++;
head = head.next;
}
return size;
}
}