1. 基于数组实现栈。
- 判断栈是否为空
- 栈顶元素
- 入栈
- 出栈
- 扩容(由于是数组,必须要进行扩容)
1. 定义变量
需要一个数组和一个指针指向栈顶元素的上一个空间(也可以指向栈顶元素,具体看要求)
private Object[] stack;
private int top;
2. 初始化
MyStack() {
stack = new Object[0];
}
3. 判断为空
public boolean isEmpty() {
return top == 0;
}
4. 扩容
public void expandCapacity(int size) {
int length = stack.length;
if (size>length){
// 扩容两倍
size = size*3/2+1;
stack = Arrays.copyOf(stack,size);
}
}
5. 栈顶元素
public T peek() {
T t = null;
if (top > 0) t = (T) stack[top - 1];
return t;
}
6. 添加元素
public void push(T t) {
expandCapacity(top+1);
stack[top] = t;
top++;
}
7. 出栈
public T pop() {
T t = peek();
if (top > 0) {
stack[top - 1] = null;
top--;
}
return t;
}
1.7 总代码
public class MyStack<T> {
private Object[] stack;
private int top;
// 初始化
MyStack() {
stack = new Object[0];
}
// 判断为空
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 length = stack.length;
if (size > length) {
// 扩容两倍
size = size * 3 / 2 + 1;
stack = Arrays.copyOf(stack, size);
}
}
}
2. 链表表示栈
- 链表Node
- Node头节点
- 判断栈空
- 栈顶元素的
- 出栈
- 入栈
1. Node和头节点
class Node<T> {
public T t;
public Node next;
}
public Node<T> head;
2. 初始化
ListStack() {
head = null;
}
3. 判断栈空
public boolean isEmpty() {
return head == null;
}
4. 栈顶元素
public T peek() {
if (head == null) {
return null;
}
return head.t;
}
2.5 出栈
public T pop() {
if (head == null) {
return null;
}
T t = head.t;
head = head.next;
return t;
}
6. 入栈
public void push(T t) {
if (t == null) {
throw new NullPointerException("null");
}
if (head == null) {
head = new Node<>();
head.t = t;
head.next = null;
} else {
Node<T> temp = head;
head = new Node<>();
head.t = t;
head.next = temp;
}
}
7. 总代码
public 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("null");
}
if (head == null) {
head = new Node<>();
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;
}
return head.t;
}
public boolean isEmpty() {
return head == null;
}
}