栈和队列面试题(Java语言实现)

1.括号匹配问题。

给定一个包含"{","}","[","]","(",")"的字符串,判断字符串是否有效。

思路:依次遍历字符串中的每个字符,如果是左括号,如“{","[","(",就入栈;如果是右括号,如”}“,”]“,”)",先判断栈是否为空,如果栈为空,说明没有元素与它匹配,一定不符合,直接返回false;如果栈不为空,取栈顶元素,看该元素是否与栈顶元素匹配,如果匹配,则继续比较,不匹配,直接返回false。遍历完所有的字符之后,如果栈为空,说明所有的括号都匹配;否则说明不匹配。

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack=new Stack<>();
        for(int i=0;i<s.length();i++){
            char c=s.charAt(i);
            switch(c){
                    //如果是左括号,就入栈。
                case '{':
                case '[':
                case '(':
                    stack.push(c);
                    break;
                case '}':
                case ']':
                case ')':{
                    //先判断栈是否为空
                    if(stack.isEmpty()){
                        return false;
                    }
                    char left=stack.pop();//取栈顶元素
                    if(!((left=='['&&c==']')||(left=='{'&&c=='}')||(left=='('&&c==')'))){
                        //如果栈顶元素和c不匹配,则直接返回false.
                        return false;
                    }
                }
                    break;
                default:
                    break;
            }
        }
        if(stack.isEmpty()){
            return true;
        }else{
            return false;
        }
    }
}

2.用队列实现栈

用队列实现栈的操作:push(int x),pop(),top(),empty()。

思路:用链表定义队列,则入栈相当于链表的尾插操作,出栈相当于尾删操作。利用链表的getLast()--返回链表的最后一个元素;removeLast()--删除并返回最后一个元素;addLast(int v)--将指定元素添加到链表末尾。

class MyStack {
    private LinkedList<Integer> queue;
    /** Initialize your data structure here. */
    public MyStack() {
        this.queue=new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        this.queue.addLast(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return this.queue.removeLast();
    }
    
    /** Get the top element. */
    public int top() {
        return this.queue.getLast();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return this.queue.size()==0?true:false;
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */

3.用两个栈实现一个队列

思路:设两个栈in和out,在in栈上入队列,如果要出队列,在out栈上进行操作。如果out栈为空,则依次将in栈中的数据出栈,并同时入栈到out栈中,最后再执行out.pop()实现出栈。判断队列为空,当in栈和out栈都是空时,队列为空。

主要使用了栈的pop()、push(E v)、isEmpty()。

class MyQueue {
    Stack<Integer> in;
    Stack<Integer> out;
    /** Initialize your data structure here. */
    public MyQueue() {
        in=new Stack<>();
        out=new Stack<>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        in.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
         if (out.isEmpty()) {
            while (!in.isEmpty()) {
                int v = in.pop();
                out.push(v);
            }
        }
        return out.pop();
    }
    
    /** Get the front element. 获取队头元素*/
    public int peek() {
        if(!out.isEmpty()){
            return out.peek();
        }
        //栈in的栈底元素
         if (out.isEmpty()) {
            while (!in.isEmpty()) {
                int v = in.pop();
                out.push(v);
            }
        }
        return out.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return in.isEmpty()&&out.isEmpty();
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */

4.实现一个最小栈

设计一个支持push,pop,top操作,并能在常数时间内检索到最小元素的栈。

push(x)--将元素x推入栈中。  pop()--删除栈顶的元素。  top()--获取栈顶元素   getMin()--检索栈中的最小元素。

思路:设计两个栈,normal和min。normal栈和正常栈的操作相同,min栈的栈顶始终存放最小元素(便于获取最小元素的时间复杂度为O(1))。psuh(x)操作,normal直接将x压栈,min栈,如果此时栈为空,那么直接入栈;否则和min栈的栈顶元素比较,如果x小于min的栈顶元素,则将x入栈。否则再将min的栈顶元素再次入栈。pop()操作,两个栈同时执行pop()。top(),normal栈中操作;getMin(),由min栈操作。

class MinStack {
    Stack<Integer> normal;
    Stack<Integer> min;//最小栈

    /** initialize your data structure here. */
    public MinStack() {
        normal=new Stack<>();
        min=new Stack<>();
    }
    
    public void push(int x) {
        normal.push(x);//直接入栈
        if(min.isEmpty()){
            min.push(x);
        }else{
            int y=x<min.peek()?x:min.peek();//将较小的值入栈
            min.push(y);
        }
    }
    
    public void pop() {
        normal.pop();
        min.pop();
    }
    
    public int top() {
        return normal.peek();
    }
    
    public int getMin() {
        return min.peek();
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */

5.设计循环队列

题目描述见https://leetcode-cn.com/problems/design-circular-queue/

class MyCircularQueue {
    private int[] array;
    private int size;
    private int front;//队首元素的下标
    private int rear;//下一个可用位置的下标

    /** Initialize your data structure here. Set the size of the queue to be k. */
    public MyCircularQueue(int k) {
        this.array=new int[k];
        this.size=0;
        this.front=0;
        this.rear=0;
    }
    
    /** Insert an element into the circular queue. Return true if the operation is successful. */
    public boolean enQueue(int value) {
        if(this.size==this.array.length){
            return false;
        }
        this.array[this.rear]=value;
        this.rear=(this.rear+1)%this.array.length;
        this.size++;
        return true;
    }
    
    /** Delete an element from the circular queue. Return true if the operation is successful. */
    public boolean deQueue() {
        if(this.size==0){
            return false;
        }
        this.front=(this.front+1)%this.array.length;
        this.size--;
        return true;
    }
    
    /** Get the front item from the queue. */
    public int Front() {
        if(this.size==0){
            return -1;
        }
        return this.array[this.front];
    }
    
    /** Get the last item from the queue. */
    public int Rear() {
         if(this.size==0){
            return -1;
        }
        int index=(this.rear-1+this.array.length)%this.array.length;
        return this.array[index];
    }
    
    /** Checks whether the circular queue is empty or not. */
    public boolean isEmpty() {
        return this.size==0;
    }
    
    /** Checks whether the circular queue is full or not. */
    public boolean isFull() {
        return this.size==this.array.length;
    }
}

/**
 * Your MyCircularQueue object will be instantiated and called as such:
 * MyCircularQueue obj = new MyCircularQueue(k);
 * boolean param_1 = obj.enQueue(value);
 * boolean param_2 = obj.deQueue();
 * int param_3 = obj.Front();
 * int param_4 = obj.Rear();
 * boolean param_5 = obj.isEmpty();
 * boolean param_6 = obj.isFull();
 */

6.栈的压入、弹出序列

题目描述:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有哦数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

import java.util.ArrayList;
import java.util.*;
/**
    思路:新建一个栈,对pushA的每个元素进行入栈,每次入栈时,都要判断popA的元素是否市栈顶元素,如果是,则进行出栈;
    同时,popA的下标++.最后如果栈不为空,说明不是;栈为空,则是。
*/
public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
        Stack<Integer> stack=new Stack<Integer>();
        if(pushA.length!=popA.length){
            return false;
        }
        int curIndex=0;
        for(int i=0;i<pushA.length;i++){
            stack.push(pushA[i]);
            if(popA[curIndex]==stack.peek()){
                stack.pop();
                curIndex++;
            }
        }
        //判断数组的出栈顺序和栈中剩下元素的出栈顺序是否相同
        while(curIndex<popA.length){
            if(stack.peek()!=popA[curIndex]){
                return false;
            }else{
                stack.pop();
            }
            curIndex++;
        }
        if(stack.isEmpty()){
            return true;
        }else{
            return false;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值