225. 用队列实现栈

转载自Leet Code

题目描述

请你仅使用两个队列实现一个后入先出(LIFO)的栈, 并支持普通栈的全部四种操作(pushtoppopempty)。

实现 MyStack 类:

  • void push(int x) 将元素 x 压入栈顶。
  • int pop() 移除并返回栈顶元素。
  • int top() 返回栈顶元素。
  • boolean empty() 如果栈是空的,返回 true ;否则,返回 false

注意:

  • 你只能使用队列的基本操作 —— 也就是 push to backpeek/pop from frontsizeis empty 这些操作。
  • 你所使用的语言也许不支持队列。 你可以使用list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。

我的代码

{.line-numbers}
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
class MyStack225 {
LinkedList<Integer> list;

/** Initialize your data structure here. */
public MyStack225()
{
list = new LinkedList();
}

/** Push element x onto stack. */
public void push(int x) {
list.add(x);
}

/** Removes the element on top of the stack and returns that element. */
public int pop() {
int []tmp = new int[list.size()];
for (int i=tmp.length-1; i>=0; i--)
tmp[i] = list.removeFirst();
int val = tmp[0];
if (tmp.length-1>=0)
for (int i=tmp.length-1; i>0; i--)
list.add(tmp[i]);
return val;
}

/** Get the top element. */
public int top() {
int []tmp = new int[list.size()];
for (int i=tmp.length-1; i>=0; i--)
tmp[i] = list.removeFirst();
int val = tmp[0];
for (int i=tmp.length-1; i>=0; i--)
list.add(tmp[i]);
return val;
}

/** Returns whether the stack is empty. */
public boolean empty() {
return list.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();
*/

方法:原地修改

可以在向队列加入新元素之前,先记录队列原本的长度n, 然后在加入新元素之后poll出前面的n个旧元素依次排到新元素后面。


代码

{.line-numbers}
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
class MyStack225 {
LinkedList<Integer> list;

/** Initialize your data structure here. */
public MyStack225()
{
list = new LinkedList();
}

/** Push element x onto stack. */
public void push(int x) {
int n = list.size();
list.add(x);
for (int i=0; i<n; i++)
list.add(list.poll());
}

/** Removes the element on top of the stack and returns that element. */
public int pop() {
return list.poll();
}

/** Get the top element. */
public int top() {
return list.peek();
}

/** Returns whether the stack is empty. */
public boolean empty() {
return list.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();
*/