栈 (先进后出、后进先出)
链表来实现栈的问题
入栈 出栈 O(1)
如果是双向链表(链式栈:此时双向链表也可以当做栈来使用)
如果是单链表 没有last这个引用
假设 从头入栈-》 O(1) 从头出:删除头结点O(1)
假设 从 尾巴入-》O(N)(有last为O(1)) 从尾巴出:O(N)
代码实现:
package stackdemo;
public class EmptyException extends RuntimeException{
public EmptyException(String msg){
super(msg);
}
}
package stackdemo;
public interface IStack {
void push(int x);
int pop();
int peek();
int size();
boolean empty();
boolean full();
}
package stackdemo;
import java.util.Stack;
class MinStack {
private Stack<Integer> stack;
private Stack<Integer> minStack;
public MinStack(){
stack = new Stack<>();
minStack = new Stack<>();
}
public void push(int val) {
stack.push(val);
if (minStack.empty()){
minStack.push(val);
}else {
int peekVal = minStack.peek();
//0 1 0
if (val <= peekVal){
minStack.push(val);
}
}
}
public void pop(){
int val = stack.pop();
if (!minStack.empty()){
if (val == minStack.peek()){
minStack.pop();
}
}
}
//peek 获取当前普通栈的栈顶元素
public Integer top(){
return stack.peek();
}
//最小栈的peek 每次通过这个方法获取最小值
public int getMin(){
if (!minStack.empty()){
return minStack.peek();
}
return -1;
}
}
package stackdemo;
import java.util.Arrays;
import java.util.Stack;
public class MyStack implements IStack{
private int[] elem;
private int usedSize; //可以存放数据元素的下标
private static final int DEFAULT_CAPACITY = 10;
public MyStack(){
elem = new int[DEFAULT_CAPACITY];
}
@Override
public void push(int x) {
if (full()){
elem = Arrays.copyOf(elem,2*elem.length); //扩容
}
elem[usedSize] = x;
usedSize++;
}
@Override
public int pop() {
if (empty()){
//return -1;
throw new EmptyException("栈空了!");
}
int old = elem[usedSize-1];
usedSize--; //相当于删除
// elem[usedSize] = null; 如果是引用类型
return old;
}
@Override
public int peek() {
if (empty()){
//return -1;
throw new EmptyException("栈空了!");
}
return elem[usedSize-1];
}
@Override
public int size() {
return usedSize;
}
@Override
public boolean empty() {
return usedSize == 0;
}
@Override
public boolean full() {
if (usedSize == elem.length){
return true;
}
return false;
}
}
package stackdemo;
import sun.awt.image.ImageWatched;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;
public class Test {
public static void main(String[] args) {
MyStack myStack = new MyStack();
//队列
Queue<Integer> queue = new LinkedList<>();
queue.offer(1);
queue.offer(2);
queue.offer(3);
queue.offer(4);
System.out.println(queue.peek());//1
System.out.println(queue.poll());//1
System.out.println(queue.poll());//2
//链表
List<Integer> queue1 = new LinkedList<>();
}
public static void main1(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
Integer ret = stack.pop();
System.out.println(ret);
ret = stack.peek(); //peek只是获取栈顶元素
System.out.println(ret);//3
ret = stack.peek();
System.out.println(ret);//3
}
}