什么是栈
栈是一种“操作受限”的线性表,只允许在一端插入和删除数据。
栈最大的特点就是“后进先出”
栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。栈的删除操作叫做出栈。出数据也在栈顶。
顺序栈和链式栈
栈既可以用数组来实现,也可以用链表来实现。用数组实现的栈,我们叫作顺序栈,用链表实现的栈,我们叫作链式栈。
数组实现一个顺序栈
public class ArrayStack {
private String[] items; // 数组
private int count; // 栈中元素个数
private int n; //栈的大小
// 初始化数组,申请一个大小为n的数组空间
public ArrayStack(int n) {
this.items = new String[n];
this.n = n;
this.count = 0;
}
public boolean push(String item) {
if(count==n){
System.out.println("栈中数据已满");
return false;
}
items[count]=item;
++count;
return true;
}
public String pop() {
if(count==0){
return "栈为空,删除失败";
}
String tem = items[count-1];
--count;
return tem;
}
}
链表实现一个链式栈
链表的尾插需要遍历寻找最后一个节点,时间复杂度为O(n),所以用头插的形式
public class LinkedListStack {
private static class Node {
private int data;
private Node next;
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
public int getData() {
return data;
}
}
private Node top = null;
public boolean push(int value) {
Node newNode = new Node(value,null);
if (top == null) {
top = newNode;
} else {
newNode.next = top;
top = newNode;
}
return true;
}
public int push() {
if (top == null) {
System.out.println("栈为空,删除失败");
return -1;
}
int value = top.data;
top = top.next;
return value;
}
}