1、概述
栈:只允许在一端操作的顺序表或链表
常用操作:empty(),peek(),pop(),push()
2、数组实现
top指针指向栈顶元素的上一位
//用数组实现栈
public 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 T pop(){
T t = peek();
if(top > 0){
stack[top - 1] = null;
top--;
}
return t;
}
//压栈
public void push(T t){
expandCapacity(top + 1);
stack[top] = t;
top++;
}
//扩容
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("a");
stack.push("b");
System.out.println(stack.peek());
System.out.println(stack.isEmpty());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.isEmpty());
}
}
3、链表实现
top指针(即head)指向栈顶元素
//自定义链表实现栈
public class ListStack<T> {
class Node<T>{
public T t;
public Node next;
}
//头指针及top指针,这种实现方式,top指的是栈顶元素,不是栈顶上一位
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<T>();
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(){
if(head == null){
return true;
}else
return false;
}
public static void main(String[] args) {
ListStack<String> stack = new ListStack<>();
System.out.println(stack.peek());
System.out.println(stack.isEmpty());
stack.push("a");
stack.push("b");
System.out.println(stack.peek());
System.out.println(stack.isEmpty());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.isEmpty());
}
}