【栈】是一种遵循先入后出逻辑的线性数据结构。
方法名 | 描述 | 时间复杂度 |
---|---|---|
push() | 向栈顶插入元素 | O(1) |
pop() | 栈顶元素出栈 | O(1) |
peek() | 访问栈顶元素 | O(1) |
1.单向链表实现
注意栈和队列用链表实现的区别,栈是只能在栈顶操作
而队列是既可以在队首操作(出队),又可以在队尾操作(入队)
类属性
public class LinkedListStack<E> {
Node<E> head = new Node<>(null, null);
private int size = 0;
private int capacity = Integer.MAX_VALUE;
public LinkedListStack(int capacity) {
this.capacity = capacity;
}
static class Node<E> {
E value;
Node<E> next;
public Node(E value, Node<E> next) {
this.value = value;
this.next = next;
}
}
}
push()方法
public boolean push(E value) {
if (isFull()) {
return false;
}
head.next = new Node<>(value, head.next);
size++;
return true;
}
pop()方法
public E pop() {
if (isEmpty()) {
return null;
}
Node<E> first = head.next;
head.next = first.next;
size--;
return first.value;
}
peek()方法
public E peek() {
if (isEmpty()) {
return null;
}
return head.next.value;
}
类内方法
public boolean isEmpty() {
return head.next == null; // 等价于 return size == 0;
}
public boolean isFull() {
return size == capacity;
}
迭代器
public Iterator<E> iterator() {
return new Iterator<E>() {
Node<E> p = head;
@Override
public boolean hasNext() {
return p != null;
}
@Override
public E next() {
E value = p.value;
p = p.next;
return value;
}
};
}
测试
public static void main(String[] args) {
LinkedListStack<Integer> stack = new LinkedListStack<>(10);
System.out.println("第一次入栈:" + "4");
stack.push(4);
System.out.println("第二次入栈:" + "9");
stack.push(9);
System.out.println("第三次入栈:" + "7");
stack.push(7);
System.out.println();
System.out.println("第一次出栈:" + stack.pop());
System.out.println("第二次出栈:" + stack.pop());
System.out.println("第三次出栈:" + stack.pop());
}
2.数组实现
栈只有一个栈顶指针 top
public class ArrayStack<E> {
private E[] array;
private int top; // 栈顶指针
public ArrayStack(int capacity) {
this.array = (E[]) new Object[capacity];
}
}
push()方法
public boolean push(E value) {
if (isFull()) {
return false;
}
array[top] = value;
top++;
return true;
}
pop()方法
public E pop() {
if (isEmpty()) {
return null;
}
E value = array[top - 1];
top--; // 直接指针下移,不用再赋值成-1
return value;
}
peek()方法
public E peek() {
if (isEmpty()) {
return null;
}
return array[top - 1];
}
类内方法
public boolean isEmpty() {
return top == 0;
}
public boolean isFull() {
return top == array.length;
}