代码随想录算法训练营第九天-232用栈实现队列、225用队列实现栈
Kiml Lv5
  • 前言
    状态:都是直接看的解析,不是很难。

  • 更新

1
24.05.30 初始记录

初步题解

232 用栈实现队列

题目链接:(https://leetcode.cn/problems/implement-queue-using-stacks/description/)

JAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class LE232 {  
public static void main(String[] args) {
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
System.out.println("queue.peek() = " + queue.peek());
System.out.println("queue.pop() = " + queue.pop());
System.out.println("queue.empty() = " + queue.empty());
}

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

public MyQueue() {
stackIn = new Stack<>();
stackOut = new Stack<>();
}

public void push(int x) {
stackIn.push(x);
}

public int pop() {
// 把in的内容复制到out
in2out();
return stackOut.pop();
}

private void in2out() {
if (stackOut.isEmpty()) {
while (!stackIn.isEmpty()) {
stackOut.push(stackIn.pop());
}
}
}

/**
* 返回列表开头的数据
* @return 结果
*/
public int peek() {
// 把in的内容复制到out
in2out();
return stackOut.peek();
}

public boolean empty() {
return stackIn.empty() && stackOut.empty();
}
}
}

225 用队列实现栈

题目链接:(https://leetcode.cn/problems/implement-queue-using-stacks/description/)

JAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class LE225 {  
public static void main(String[] args) {
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
System.out.println("myStack.top() = " + myStack.top());
System.out.println("myStack.pop() = " + myStack.pop());
System.out.println("myStack.empty() = " + myStack.empty());
}

static class MyStack {
Queue<Integer> queue;

public MyStack() {
queue = new LinkedList<>();
}

public void push(int x) {
queue.offer(x);
int size = queue.size() - 1;
while (size != 0) {
size--;
queue.offer(queue.poll());
}
}

public int pop() {
return queue.poll();
}

public int top() {
return queue.peek();
}

/**
* 判断是否为空
*/
public boolean empty() {
return queue.isEmpty();
}
}
}

看讲解

232 用栈实现队列

题目链接/文章讲解/视频讲解:(https://programmercarl.com/0232.用栈实现队列.html)

思路:用栈模拟队列需要两个栈。一个栈作为入栈,一个栈作为出栈。如果出栈为空,将入栈中的元素压入出栈。

image

225 用队列实现栈

题目链接/文章讲解/视频讲解:(https://programmercarl.com/0225.用队列实现栈.html)

思路:用队列模拟栈,可以只用一个队列。每当有新元素入队列,将原有的旧元素重新入队列,这样新元素就变成栈顶元素。(一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时再去弹出元素就是栈的顺序了。

image

 评论
评论插件加载失败
正在加载评论插件
由 Hexo 驱动 & 主题 Keep v4.2.5
访客数 609 访问量 2518