-
Notifications
You must be signed in to change notification settings - Fork 0
/
CreateStackFromQueue.java
83 lines (69 loc) · 1.89 KB
/
CreateStackFromQueue.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// class MyStack {
// Queue<Integer> q = new LinkedList<Integer>();
// /** Initialize your data structure here. */
// int top = 0;
// int length = 0;
// public MyStack() {
// }
// /** Push element x onto stack. */
// public void push(int x) {
// q.add(x);
// top = x;
// length++;
// }
// /** Removes the element on top of the stack and returns that element. */
// public int pop() {
// int temp = length;
// for (int i = temp; i > 1; i--) {
// int val = q.poll();
// q.add(val);
// top = val;
// }
// length--;
// return q.poll();
// }
// /** Get the top element. */
// public int top() {
// if (!empty()) return top;
// return -1;
// }
// /** Returns whether the stack is empty. */
// public boolean empty() {
// return q.isEmpty();
// }
// }
class MyStack {
Queue<Integer> q = new LinkedList<Integer>();
/** Initialize your data structure here. */
public MyStack() {
}
/** Push element x onto stack. */
public void push(int x) {
q.add(x);
//Move last element to first
for (int i = 0; i < q.size() - 1; i++) {
int val = q.poll();
q.add(val);
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q.poll();
}
/** Get the top element. */
public int top() {
return q.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q.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();
*/