Day 10 | 232. Implement Queue using Stacks | 225. Implement Stack using Queue

这篇博客介绍了如何利用栈和队列的基本概念来实现LeetCode上的232题(用栈实现队列)和225题(用队列实现栈)。在232题中,通过两个栈来模拟队列的push、pop、peek和empty操作;而在225题中,博主提供了两种方法实现用队列实现栈,一种是使用两个队列,另一种是仅使用一个队列并重新排序。文章详细阐述了每种方法的思路和实现过程。

Day 1 | 704. Binary Search | 27. Remove Element | 35. Search Insert Position | 34. First and Last Position of Element in Sorted Array


Basic Concept of the Stack and the Queue

  • The stack is last-in-fist-out(LIFO
  • The queue is first in first out(FIFO
  • They don’t allow traversal, and don’t provide the iterator.
  • The stack use pluggable containers to implement its function and provide unified interfaces to the outside world. That is, we can control what container to implement the part of the stack.

LeetCode 232. Implement Queue using Stacks

Question Link

Solution:

class MyQueue {
    Stack<Integer> stackIn;
    Stack<Integer> stackOut; 

    // Initiallize the data structure
    public MyQueue() { 
        stackIn = new Stack<>();  
        stackOut = new Stack<>();
    }
    
    public void push(int x) {
        stackIn.push(x);
    }
    
    public int pop() {
        dumpStackIn();
        return stackOut.pop();
    }
    
    public int peek() {
        dumpStackIn();
        return stackOut.peek();
    }
    
    public boolean empty() {
        return stackIn.isEmpty()&&stackOut.isEmpty();
    }

    //If the stackOut is empty, dump all of the elements of the stackIn into the stackOut
    private void dumpStackIn(){
        if(!stackOut.isEmpty())
            return;
        while(!stackIn.isEmpty()){
            stackOut.push(stackIn.pop());
        }
    }
}

/**
 * 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();
 */

Thought:

  • When popping the stack:
    • If the stackOut is empty, dump all of the elements of the stackIn into the stackOut. Then do pop() from the stackOut
    • If the stackOut is not empty, do pop() directly from the stackOut

LeetCode 225. Implement Stack using Queues

Question Link

Solution:
1、Use two queues for implementation

class MyStack {
    Queue<Integer> queue1;
    Queue<Integer> queue2; // auxiliary queue for backup
    public MyStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }
    
    public void push(int x) {
        // put x in to auxiliary queue first
        queue2.offer(x);
        // then dump all elements of the queue1 in to the queue2
        while(!queue1.isEmpty())
            queue2.offer(queue1.poll());
        // dump all elements of the queue2 into queue1
        Queue<Integer> queueTemp = new LinkedList<>();
        queue1 = queue2;
        queue2 = queueTemp;
    }   
    
    public int pop() {
       return queue1.poll();
    }
    
    public int top() {
        return queue1.peek();
    }
    
    public boolean empty() {
        return queue1.isEmpty();
    }
}

/**
 * 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();
 */

Thought:

  • Put x in to auxiliary queue2 first
  • Dump all elements of the queue1 in to the queue2
  • Dump all elements of the queue2 into queue1

2、Use one queue for implementation

class MyStack {
    Queue<Integer> queue;
    public MyStack() {
        queue = new LinkedList<>();
    }
    
    // When push a `x`, reorder the queue. Put the `x` at the front of the queue
    public void push(int x) {
        queue.offer(x);
        int size = queue.size();
        // move all of the elements except `x`
        while(size-- > 1)
            queue.offer(queue.poll());
    }   
    
    public int pop() {
       return queue.poll();
    }
    
    public int top() {
        return queue.peek();
    }
    
    public boolean empty() {
        return queue.isEmpty();
    }
}

/**
 * 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();
 */

Thought:

  • When push a x, reorder the queue. Put the x at the front of the queue
  • In the while loop, move all of the elements except x
The goal of task 1 The goal of this exercise is to implement a Stack data structure. The implementation must pass all the tests included in the exercise. Time complexity requirements: capacity(): O(1). push(): O(1), except for when reallocation must be done: O(n). pop(): O(1). peek(): O(1). size(): O(1). isEmpty(): O(1). toString(): O(n). clear(): O(1). When implementing clear() you may decide yourself if you want to keep the current capacity or will the capacity be the default capacity of a queue. Note that the method toString() in this and later execises must be implemented using Java StringBuilder, not by using the String by modifying and appending to a String object. When handling large amounts of data elements, with String, this is hundreds of times slower than using StringBuilder. This has already been implemented for you. Prerequisites You have all the tools installed and working. This was tested in the 00-init exercise of the course. If you haven't done that yet, do it now. Instructions An overview of the classes in this exercise is shown in the UML class diagram below. Note that in this task, you only work with the StackImplementation class. The class ParenthesisTChecker.java and StackFactory.createCharacterStack() are not needed until you start working with the additional tasks. If you want to, you may crete your own main app file, for example in src/main/java/oy/tol/tra/Main.java, where you may implement your own main() method to experiment with your stack implementation. However, the main goal of the exercise is to pass all the unit tests. Do not implement main() method to data structure classes or test classes! Before delivery, remove all main functions an any unnrcessary test code. UML class diagram You should implement the interface StackInterface in the StackImplementation.java which is already created for you and located in this project's src/main/java/oy/tol/tra/ directory! Note that the StackImplementation uses E template parameter for the StackInterface: public class StackImplementation<E> implements StackInterface<E> { So the stack is a generic (template) class. Make sure to read the StackInterface documentation (the comments in the code) carefully so that your implementation follows the interface documentation. Obviously you need to know how stacks work in general, so check out the course lectures and other material on stack data structures. In this exercise, you use the Java plain array as the internal data structure for holding the elements: private Object [] itemArray; Since all Java classes inherit from Object, we can create an array of Objects for the elements. In the StackImplemention, constructors, follow the code comments and allocate the array of elements, in addition to other things you need to implement: itemArray = new Object[capacity]; Make sure to implement reallocating more room in the StackImplementation internal array if array is already full, when push() is called! After you have implemented your stack class methods, you can see that it is already instantiated for you in StackFactory.createIntegerStack(). After this, you are ready to test your implementation.
03-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值