数据结构之栈与队列

数据结构之栈与队列

先进后出的一种数据结构(FILO)

示意图

在这里插入图片描述

简单实现

public class Node<T> {
    T data;
    Node next;

    public Node(){
        this.next = null;
    }

    public Node(T date){
        this.next = null;
        this.data = date;
    }
}
public class Stack<T> {
    Node<T> top;
    Node<T> bottom;
    int size;

    public Stack(){
        this.top = new Node<>();
        this.size = 0;
    }

    public boolean isEmpty(){
        return top.next == null;
    }

    public void push(Node<T> node){
        if(this.size == 0){
            this.top.next = node;
        }else {
            node.next = this.top.next;
            this.top.next = node;
        }
        size++;
    }

    public Node<T> pop(){
        Node node = this.top.next;
        if(this.top.next != null){
            this.top.next = this.top.next.next;
            node.next = null;
        }
        return node;
    }

    public void printStack(){
        Node point = this.top;
        while(point.next != null){
            System.out.print(point.next.data+" ");
            point = point.next;
        }
        System.out.println();
    }

    public void clear(){
        this.top = new Node<>();
        this.size = 0;
    }

    public Object top(){

        return this.top.next.data;
    }

}

应用

应对匹配就用栈

判断一个序列是否是回文序列
public class IsPalindrome {
    public static void main(String[] args) {
        System.out.println(isPalindrome("12344321"));
    }

    public static boolean isPalindrome(String str){
        char[] chars = new char[str.length()*2 + 1];
        char[] s = str.toCharArray();
        for (int index1 = 0,index2=0; index1 < s.length; index1++,index2++) {
            chars[index2] = '|';
            index2++;
            chars[index2] = s[index1];
        }
        chars[str.length()*2] = '|';
        System.out.println(new String(chars));
        Stack<Character> stack  = new Stack<>();

        for (int index = 0; index < chars.length; index++) {
           if(index < str.length()){
               stack.push(new Node<Character>(chars[index]));
           }else if(index > str.length()){
               char temp = stack.pop().data;
               if(temp != chars[index]){
                   return false;
               }
           }
        }
        return true;
    }
}
判断括号合法性
public class Match {
    public static void main(String[] args) {
		//合法的括号序列必须是可以闭合的
        System.out.println(match("{[(){}()()]}"));
    }
    public static boolean match(String str){
        char[] chars = str.toCharArray();
        Stack<Character> stack = new Stack<>();
        for (int index = 0; index < chars.length; index++) {
            if(!stack.isEmpty()) {
                char temp = stack.pop().data;
                if((temp == '(' && chars[index] != ')') ||(temp == '{' && chars[index] != '}')||(temp == '[' && chars[index] != ']')){
                    stack.push(new Node<Character>(temp));
                    stack.push(new Node<Character>(chars[index]));
                }
            }else {
                stack.push(new Node<Character>(chars[index]));
            }
        }
        return stack.isEmpty();
    }
}

单调栈

单调栈就是栈只会存储递增或者递减的序列的栈。即在栈中维护一个单调的序列。

应用
力扣42.接雨水

示例

输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
输出:6
解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。

代码实现

class Solution {
    public int trap(int[] height) {
        //单调栈
        Stack<Integer> stack = new Stack();
        //遍历元素,如果找到比栈顶元素大的,那么栈顶元素就是极小值
        stack.push(0);
        int sum = 0;
        for(int i = 1; i < height.length;i++){
            while(!stack.isEmpty() && height[i] > height[stack.peek()]){
                int mid = stack.pop();
                if(!stack.isEmpty()){
                    int h = Math.min(height[stack.peek()] ,height[i]) - height[mid];
                    int w = i - stack.peek() - 1;
                    if(h*w>0)
                    sum += h * w;
                }
            }   
            stack.push(i);
        }
        return sum;
    }
}

队列

先进先出的一种数据结构(FIFO)

示意图

简单实现

public class Node<T> {
    T data;
    Node next;

    public Node(){
        this.next = null;
    }

    public Node(T date){
        this.next = null;
        this.data = date;
    }
}
public class Queue<T> {
    //queueHead
    Node<T> head = new Node<T>();
    //queueTail
    Node tail;
    //size
    int size;


    public Queue(){
         size = 0;
    }

    //isEmpty
    public boolean isEmpty(){
        return this.head.next == null;
    }

    //in
    public void push(Node<T> node){
        if(this.size == 0){
            this.head.next = node;
            this.tail = node;
        }else {
            this.tail.next = node;
            this.tail = this.tail.next;
        }
        size++;
    }

    //out
    public Node<T> pop(){
        Node<T> node = this.head.next;
        if(head.next!=null){
            head.next = head.next.next;
        }
        size--;
        return node;
    }


    public  void printQueue(){
        Node<T> point = this.head;
        while(point.next!=null){
            System.out.print(point.next.data+" ");
            point = point.next;
        }
        System.out.println();
    }
}

单调队列

单调队列就是值让符合递增或者递减的序列进修。即在队列里维护一个单调的序列。

应用
力扣239.滑动窗口的最大值

示例

输入:nums = [1,3,-1,-3,5,3,6,7], k = 3
输出:[3,3,5,5,6,7]
解释:
滑动窗口的位置                最大值
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7

代码实现

class MyQueue {
    Deque<Integer> deque = new LinkedList<>();
    //弹出元素时,比较当前要弹出的数值是否等于队列出口的数值,如果相等则弹出
    //同时判断队列当前是否为空
    void poll(int val) {
        if (!deque.isEmpty() && val == deque.peek()) {
            deque.poll();
        }
    }
    //添加元素时,如果要添加的元素大于入口处的元素,就将入口元素弹出
    //保证队列元素单调递减
    //比如此时队列元素3,1,2将要入队,比1大,所以1弹出,此时队列:3,2
    void add(int val) {
        while (!deque.isEmpty() && val > deque.getLast()) {
            deque.removeLast();
        }
        deque.add(val);
    }
    //队列队顶元素始终为最大值
    int peek() {
        return deque.peek();
    }
}

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if (nums.length == 1) {
            return nums;
        }
        int len = nums.length - k + 1;
        //存放结果元素的数组
        int[] res = new int[len];
        int num = 0;
        //自定义队列
        MyQueue myQueue = new MyQueue();
        //先将前k的元素放入队列
        for (int i = 0; i < k; i++) {
            myQueue.add(nums[i]);
        }
        res[num++] = myQueue.peek();
        for (int i = k; i < nums.length; i++) {
            //滑动窗口移除最前面的元素,移除是判断该元素是否放入队列
            myQueue.poll(nums[i - k]);
            //滑动窗口加入最后面的元素
            myQueue.add(nums[i]);
            //记录对应的最大值
            res[num++] = myQueue.peek();
        }
        return res;
    }
}

双端队列

即队列可以左进右出,也可以右进左出

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值