当前位置:网站首页>LeetCode-栈和队列刷题
LeetCode-栈和队列刷题
2022-07-24 02:45:00 【[email protected]】
写在前面:复习完栈和队列的基础知识,然后通过leetcode的几道题目加深理解,更多的是对于栈和队列的运用,而没有对于栈和队列操作的具体实现
文章目录
题目一
622. 设计循环队列
设计你的循环队列实现。 循环队列是一种线性数据结构,其操作表现基于 FIFO(先进先出)原则并且队尾被连接在队首之后以形成一个循环。它也被称为“环形缓冲器”。
循环队列的一个好处是我们可以利用这个队列之前用过的空间。在一个普通队列里,一旦一个队列满了,我们就不能插入下一个元素,即使在队列前面仍有空间。但是使用循环队列,我们能使用这些空间去存储新的值。
你的实现应该支持如下操作:
MyCircularQueue(k): 构造器,设置队列长度为 k 。
Front: 从队首获取元素。如果队列为空,返回 -1 。
Rear: 获取队尾元素。如果队列为空,返回 -1 。
enQueue(value): 向循环队列插入一个元素。如果成功插入则返回真。
deQueue(): 从循环队列中删除一个元素。如果成功删除则返回真。
isEmpty(): 检查循环队列是否为空。
isFull(): 检查循环队列是否已满。
题目解答
注意事项:
- ArrayList 是变长数组,不需要设置长度,使用方法
ArrayList<Integer> arrayList = new ArrayList<>();
该题采用数组来实现即可
- 队列是尾部进,头部出
题目中的headIndex表示的是头部的索引,所以入队时是不需要变化headIndex的
class MyCircularQueue {
Integer[] Q;
int headIndex;
int count;
int length;
public MyCircularQueue(int k) {
Q = new Integer[k];
headIndex = 0;
count = 0;
length = k;
}
public boolean enQueue(int value) {
if(count == length){
return false;
}
else{
Q[(headIndex + count) % length] = value;
count++;
return true;
}
}
public boolean deQueue() {
if(count == 0){
return false;
}
else{
count--;
headIndex = (headIndex +1 ) % length;
return true;
}
}
public int Front() {
if(count == 0){
return -1;
}
return Q[headIndex];
}
public int Rear() {
if(count == 0){
return -1;
}
//System.out.println((headIndex + count)%length);
return Q[(headIndex + count - 1) % length];
}
public boolean isEmpty() {
return (count == 0);
}
public boolean isFull() {
return (count == 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(); */
题目二
232. 用栈实现队列
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false
说明:
你 只能 使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
题目解答
class MyQueue {
Stack<Integer> a;
Stack<Integer> b;
public MyQueue() {
a = new Stack<Integer>();
b = new Stack<Integer>();
}
public void push(int x) {
a.push(x);
}
public int pop() {
if(!b.isEmpty()){
return b.pop();
}
else{
while(!a.isEmpty()){
b.push(a.pop());
}
return b.pop();
}
}
public int peek() {
if(!b.isEmpty()){
return b.peek();
}
else{
while(!a.isEmpty()){
b.push(a.pop());
}
return b.peek();
}
}
public boolean empty() {
return a.isEmpty() && b.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(); */
题目三
225. 用队列实现栈
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
注意:
你只能使用队列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。
你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
题目解答
class MyStack {
Queue<Integer> Q1;
Queue<Integer> Q2;
public MyStack() {
Q1 = new LinkedList<Integer>();
Q2 = new LinkedList<Integer>();
}
public void push(int x) {
Q2.offer(x);
while(!Q1.isEmpty()){
Q2.offer(Q1.poll());
}
Queue<Integer> temp = new LinkedList<Integer>();
temp = Q1;
Q1 = Q2;
Q2 = temp;
}
public int pop() {
return Q1.poll();
}
public int top() {
return Q1.peek();
}
public boolean empty() {
return Q1.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(); */
版权声明
本文为[[email protected]]所创,转载请带上原文链接,感谢
https://blog.csdn.net/Little_jcak/article/details/125901240
边栏推荐
- QT display Chinese garbled code
- Go basic notes_ 5_ Array slice
- 攻防世界WEB練習區(view_source、get_post、robots)
- Recorded on July 21, 2022
- Mysql database, grouping function
- Jina AI 联合Datawhale,发起学习项目!
- How to judge null for different types of fields, sets, lists / sets / maps, and objects
- Recommendation system topic | recommendation system architecture and single domain cross domain recall model
- Liveqing live RTMP on demand video streaming platform how to carry the Sid and token returned by the login interface to call authentication streamtoken video streaming authentication
- Liveqing live broadcast on demand streaming media OBS streaming live broadcast how to obtain interface verification token video verification streamtoken and configure token validity
猜你喜欢

Understand the low code implementation of microservices

SSM's technical forum includes front and back offices

营员招募|心怀世界的AI青年们,联合国需要你为可持续发展助力!

攻防世界WEB练习区(backup、cookie、disabled_button)

Attack and defense world web practice area (backup, cookie, disabled_button)

Essential skills for programmers -- breakpoint debugging (idea version)

记于2022.7.21

Nirvana rebirth! Byte Daniel recommends a large distributed manual, and the Phoenix architecture makes you become a God in fire

7 issues to consider before website construction

如何获取步态能量图gei
随机推荐
To forge ahead on a new journey, the city chain science and technology carnival was grandly held in Xiamen
La chaîne entrante a des données lors de la transmission des paramètres JS; Aucune donnée n'a été transmise au numéro; 2 [0] Oui! Les données de type numéro peuvent être indexées
Is it safe to open an account for Xiaobai stock? Can I apply online?
Implementation of POP3 client code
攻防世界WEB练习区(view_source、get_post、robots)
The practical influence of educational robot on students' learning effect
[FPGA tutorial case 38] communication case 8 - serial parallel serial data transmission based on FPGA
微信小程序實現折線面積圖-玫瑰圖-立體柱狀圖
[diary of supplementary questions] [2022 Hangdian summer school 1] b-dragon Slayer
数据湖(十五):Spark与Iceberg整合写操作
Do securities companies really have principal guaranteed financial products?
[FPGA tutorial case 39] communication case 9 - interleaving deinterleaving data transmission based on FPGA
Job hunting and recruitment system of SSM part-time job hunting
攻防世界WEB练习区(weak_auth、simple_php、xff_referer)
Doodle icons - a free commercial graffiti style icon library, cute, light and unique
JpaRepository扩展接口
Crop leaf disease identification system
记于2022.7.21
营员招募|心怀世界的AI青年们,联合国需要你为可持续发展助力!
Jparepository extension interface