算法通关村——如何基于数组(或者链表)实现栈
栈
- 栈的定义:
- 访问受限的线性表
- 栈的底层仍然是链表或者顺序表
- 栈的插入和删除只能在线性表的一段进行操作
- 一般而言,top的指向是指栈顶在往上一个空单位,具体情况问面试官
基于数组实现栈
class Mystack<T> {
private Object[] stack;
private int top;
Mystack() {
stack = new Object[10];
}
public boolean isEmpty() {
return top == 0;
}
public T peek() {
T t = null;
if (top > 0)
t = (T) stack[top - 1];
return t;
}
public void push(T t) {
expandCapacity(top + 1);
stack[top] = t;
top++;
}
public T pop() {
T t = peek();
if (top > 0) {
stack[top - 1] = null;
top--;
}
return t;
}
public void expandCapacity(int size) {
int len = stack.length;
if (size > len) {
size = size * 3 / 2 + 1;
stack = Arrays.copyOf(stack, size);
}
}
public static void main(String[] args) {
Mystack<String> stack = new Mystack<>();
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());
}
}
基于链表实现栈
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());
}
}