当前位置:网站首页>Leetcode skimming: stack and queue 02 (realizing stack with queue)
Leetcode skimming: stack and queue 02 (realizing stack with queue)
2022-07-02 00:26:00 【Taotao can't learn English】
225. Using queue to implement stack
Use queues to implement the following operations of the stack :
- push(x) – Elements x Push
- pop() – Remove the top element
- top() – Get stack top element
- empty() – Whether the return stack is empty
Be careful :
- You can only use the basic operations of the queue -- That is to say push to back, peek/pop from front, size, and is empty These operations are legal .
- The language you use may not support queues . You can use list perhaps deque( deque ) To simulate a queue , As long as it's a standard queue operation .
- You can assume that all operations are valid ( for example , No call to an empty stack pop perhaps top operation ).
For this question , First of all, we need to know several methods
- pop Stack exit element
- push Put elements at the end of the stack
- peek Look at the top of the stack
- offer Team tail in element
- poll The first element of the team
- peek View queue elements
I use it ArrayDeque Simulated . Actually check API This class has many duplicate methods .
boolean add(E e)
Inserts the specified element at the end of this double ended queue .
void addFirst(E e)
Inserts the specified element at the beginning of this double ended queue .
void addLast(E e)
Inserts the specified element at the end of this double ended queue .
void clear()
Remove all elements from this double ended queue .
ArrayDeque clone()
Return a copy of this double ended queue .
boolean contains(Object o)
If this double ended queue contains the specified element , Then return to true.
Iterator descendingIterator()
Returns an iterator that iterates over the elements of this two-way queue in reverse order .
E element()
obtain , But do not remove the head of the queue represented by this double ended queue .
E getFirst()
obtain , But do not remove the first element of this double ended queue .
E getLast()
obtain , But do not remove the last element of this double ended queue .
boolean isEmpty()
If this double ended queue does not contain any elements , Then return to true.
Iterator iterator()
Returns the iterator that iterates over the elements of this double ended queue .
boolean offer(E e)
Inserts the specified element at the end of this double ended queue .
boolean offerFirst(E e)
Inserts the specified element at the beginning of this double ended queue .
boolean offerLast(E e)
Inserts the specified element at the end of this double ended queue .
E peek()
obtain , But do not remove the head of the queue represented by this double ended queue ; If this double ended queue is empty , Then return to null.
E peekFirst()
obtain , But do not remove the first element of this double ended queue ; If this double ended queue is empty , Then return to null.
E peekLast()
obtain , But do not remove the last element of this double ended queue ; If this double ended queue is empty , Then return to null.
E poll()
Get and remove the header of the queue represented by this double ended queue ( let me put it another way , The first element of this two-way queue ); If this double ended queue is empty , Then return to null.
E pollFirst()
Gets and removes the first element of this double ended queue ; If this double ended queue is empty , Then return to null.
E pollLast()
Get and remove the last element of this two-way queue ; If this double ended queue is empty , Then return to null.
E pop()
Pop an element from the stack represented by this double ended queue .
void push(E e)
Push the element into the stack represented by this double ended queue .
E remove()
Get and remove the header of the queue represented by this double ended queue .
boolean remove(Object o)
Remove a single instance of the specified element from this double ended queue .
E removeFirst()
Gets and removes the first element of this double ended queue .
boolean removeFirstOccurrence(Object o)
Remove the specified element that first appears in this double ended queue ( When traversing a double ended queue from head to tail ).
E removeLast()
Get and remove the last element of this two-way queue .
boolean removeLastOccurrence(Object o)
Remove the last occurrence of the specified element in this double ended queue ( When traversing a double ended queue from head to tail ).
int size()
Returns the number of elements in this double ended queue .
Object[] toArray()
Returns an array containing all the elements of this double ended queue in the proper order ( From the first element to the last element ).
T[]
toArray(T[] a)
Returns an array containing all the elements of this double ended queue in the proper order ( From the first element to the last element ); The runtime type of the returned array is the runtime type of the specified array .
package com.programmercarl.stacks_queues;
import java.util.ArrayDeque;
/** * @ClassName MyStack * @Descriotion TODO * @Author nitaotao * @Date 2022/6/29 12:10 * @Version 1.0 * https://leetcode.cn/problems/implement-stack-using-queues/ * 225. Using queue to implement stack * Ideas : * Stack First in, then out Can only A End entry ,A hold sth. level with both hands * queue fifo Can only A End entry ,B hold sth. level with both hands * pop Stack exit element * push Put elements at the end of the stack * peek Look at the top of the stack * * offer Team tail in element * poll The first element of the team * peek View queue elements * * **/
public class MyStack {
// Source queue
private ArrayDeque queueOrigin;
// Copy queue
private ArrayDeque queueCopy;
public MyStack() {
queueOrigin = new ArrayDeque();
queueCopy = new ArrayDeque();
}
/** * Push an element * @param x */
public void push(int x) {
// Push data at the end of the source queue
queueOrigin.offer(x);
}
/** * Launch an element * @return */
public int pop() {
/** * The source queue removes The last element , All other elements are pushed into the replication queue */
int lenOrigin = queueOrigin.size();
while (lenOrigin > 1) {
queueCopy.offer(queueOrigin.poll());
lenOrigin--;
}
// Get the value to be pushed
int result = (int) queueOrigin.poll();
/** * Copy the queue and push all elements into the original queue */
int lenCopy = queueCopy.size();
while (lenCopy > 0) {
queueOrigin.offer(queueCopy.poll());
lenCopy--;
}
return result;
}
/** * View top element * @return */
public int top() {
/** * The source queue removes The last element , All other elements are pushed into the replication queue */
int lenOrigin = queueOrigin.size();
while (lenOrigin > 1) {
queueCopy.offer(queueOrigin.poll());
lenOrigin--;
}
// Get the value to be pushed
int result = (int) queueOrigin.peek();
queueCopy.offer(queueOrigin.poll());
/** * Copy the queue and push all elements into the original queue */
int lenCopy = queueCopy.size();
while (lenCopy > 0) {
queueOrigin.offer(queueCopy.poll());
lenCopy--;
}
return result;
}
/** * Sentenced to empty * @return */
public boolean empty() {
return queueOrigin.size() == 0;
}
}

In fact, it's not easy to think , After all, every time you use elements, you have to put all the elements in another place , Take this element again . This kind of inefficient and farting thing is unnecessary in reality . Code is not hard , There are notes , Just look for yourself .
边栏推荐
- 【CTF】bjdctf_2020_babystack2
- Is the securities account given by qiniu business school safe? Where can I open an account
- Node——生成微信权限验证配置
- [cmake] cmake configuration in QT Creator
- 九州云与英特尔联合发布智慧校园私有云框架,赋能教育新基建
- Intelligent operation and maintenance practice: banking business process and single transaction tracking
- 启牛学院开户安全的吗?开户怎么开?
- 一个实习生的CnosDB之旅
- 2023款雷克萨斯ES产品公布,这回进步很有感
- Windows installation WSL (II)
猜你喜欢
![Data analysis methodology and previous experience summary [notes dry goods]](/img/00/e4c4cf37f1ca9134546f970d800226.png)
Data analysis methodology and previous experience summary [notes dry goods]
![[QT] solve the problem that QT MSVC 2017 cannot compile](/img/35/e458fd437a0bed4bace2d6d65c9ec8.png)
[QT] solve the problem that QT MSVC 2017 cannot compile

Export default the exported object cannot be deconstructed, and module Differences between exports

回顾数据脱敏系统

Ldr6035 smart Bluetooth audio can be charged and released (5.9.12.15.20v) fast charging and fast releasing device charging

使用多线程Callable查询oracle数据库

使用 ES 实现疫情地图或者外卖点餐功能(含代码及数据)

The new version of graphic network PDF will be released soon

Correlation - intra group correlation coefficient

Windows10 install WSL (I) (wslregisterdistribution error)
随机推荐
I would like to ask, which securities is better for securities account opening? Is it safe to open a mobile account?
Linux centos7 installation Oracle11g super perfect novice tutorial
SQL数据分析之流程控制语句【if,case...when详解】
Guide d'installation du serveur SQL
ThreadLocal内存泄漏是什么,怎么解决
Shell custom function
2023款雷克萨斯ES产品公布,这回进步很有感
[cascade classifier training parameters] training Haar cascades
二叉搜索树的创建,查找,添加,删除操作
Kyushu cloud and Intel jointly released the smart campus private cloud framework, enabling new infrastructure for education
What is the purpose of ERP project implementation plan?
Node——Egg 创建本地文件访问接口
Multi table operation - one to one, one to many and many to many
GaussDB(for MySQL) :Partial Result Cache,通过缓存中间结果对算子进行加速
Jielizhi, production line assembly link [chapter]
What is ThreadLocal memory leak and how to solve it
PWN attack and defense world cgpwn2
Practical calculation of the whole process of operational amplifier hysteresis comparator
【QT】对于Qt MSVC 2017无法编译的问题解决
Node——添加压缩文件