1. 栈基础
栈的特征:
- 存取受限的线性表
- 后进先出
栈的操作:
- push()
- pop()
- peek()
- empty()
2.数组实现栈
限制数组的存取规则,实现后进先出。注意数组边界的处理
public class Stack1<T> {
private Object[] stack;
private int top;
//初始容量
Stack1(){
stack = new Object[10];
}
public boolean isEmpty(){
return top == 0;
}
public T peek(){
if (top == 0){
throw new EmptyStackException();
}
return (T) stack[top-1];
}
public void push(T oj){
expandSize(top + 1);
stack[top] = oj;
top++;
}
public T pop(){
T peek = peek();
stack[top - 1] = null;
top--;
return peek;
}
public void expandSize(int size){
int len = stack.length;
if(size > len){
size = len * 2;
stack = Arrays.copyOf(this.stack, size);
}
}
public static void main(String[] args) {
Stack1<String> stack = new Stack1<>();
// System.out.println(stack.peek());
System.out.println(stack.isEmpty());
stack.push("java");
stack.push("is");
stack.push("beautiful");
stack.push("language");
System.out.println(stack.pop());
System.out.println(stack.isEmpty());
System.out.println(stack.peek());
}
}
3.链表实现栈
使用头插法,达到后进先出效果
class ListStack<T> {
//定义链表
class Node<T> {
public T t;
public Node next;
}
public Node<T> head;
//构造函数初始化头指针
ListStack() {
head = null;
}
//入栈
public void push(T t) {
if (t == null) {
throw new NullPointerException("参数不能为空");
}
if (head == null) {
head = new Node<T>();
head.t = t;
head.next = null;
} else {
Node<T> temp = head;
head = new Node<>();
head.t = t;
head.next = temp;
}
}
//出栈
public T pop() {
if (head == null) {
return null;
}
T t = head.t;
head = head.next;
return t;
}
//取栈顶元素
public T peek() {
if (head == null) {
return null;
}
T t = head.t;
return t;
}
//栈空
public boolean isEmpty() {
if (head == null)
return true;
else
return false;
}
public static void main(String[] args) {
ListStack stack = new ListStack();
System.out.println(stack.isEmpty());
stack.push("Java");
stack.push("is");
stack.push("beautiful");
System.out.println(stack.peek());
System.out.println(stack.pop());
System.out.println(stack.isEmpty());
}
}