My code:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
class MyStack {
private Queue<Integer> q = new LinkedList<Integer>();
// Push element x onto stack.
public void push(int x) {
q.offer(x);
}
// Removes the element on top of the stack.
public void pop() {
if (q.isEmpty())
return;
ArrayList<Integer> temp = new ArrayList<Integer>(q.size());
int len = q.size();
for (int i = 0; i < len; i++) {
temp.add(q.poll());
}
for (int i = 0; i < len - 1; i++)
q.offer(temp.get(i));
}
// Get the top element.
public int top() {
if (q.isEmpty())
return - 1;
ArrayList<Integer> temp = new ArrayList<Integer>(q.size());
int len = q.size();
for (int i = 0; i < len; i++) {
temp.add(q.poll());
}
int ret = temp.get(temp.size() - 1);
for (int i = 0; i < len; i++)
q.offer(temp.get(i));
return ret;
}
// Return whether the stack is empty.
public boolean empty() {
return q.isEmpty();
}
public static void main(String[] args) {
MyStack test = new MyStack();
test.push(1);
System.out.println(test.top());
}
}
昨天跟人吹牛,導(dǎo)致今天早上連簡(jiǎn)單題都做不出來(lái)了。
不是做不出來(lái),而是腦子用不動(dòng)了。感覺(jué)昨天用腦過(guò)度了。然后又沒(méi)睡好。
這道題目有個(gè)注意點(diǎn)是我沒(méi)考慮到的,雖然是簡(jiǎn)單題。
ArrayList<Integer> t = new ArrayList<Integer>(10);
那么, t.size() 等于多少?
我誤認(rèn)為了10
其實(shí)不是,還是0.
ArrayList 之前總結(jié)過(guò)。
這個(gè)10,表示申請(qǐng)了一個(gè)Object[]數(shù)組,長(zhǎng)度為10.
但是,不代表 arraylist size = 10.
size 仍然是0.
他和object數(shù)組長(zhǎng)度是無(wú)關(guān)的,他等于,object 數(shù)組中有效元素的個(gè)數(shù)。
剛開(kāi)始初始化的時(shí)候,數(shù)組里面都是null,所以size = 0
**
總結(jié): ArrayList size 的具體意義
**
Anyway, Good luck, Richardo!
My code:
class MyStack {
private Queue<Integer> q = new LinkedList<Integer>();
// Push element x onto stack.
public void push(int x) {
q.offer(x);
int size = q.size();
while (size > 1) {
q.offer(q.remove());
size--;
}
}
// Removes the element on top of the stack.
public void pop() {
q.poll();
}
// Get the top element.
public int top() {
return q.peek();
}
// Return whether the stack is empty.
public boolean empty() {
return q.isEmpty();
}
}
我以為有更好的方法,沒(méi)想到還是如此:
push O(n)
pop O(1)
然后可以用Queue來(lái)完成。
reference:
https://leetcode.com/articles/implement-stack-using-queues/#approach-1-two-queues-push-o1-pop-on
還有種O(1)的方法,太偏門(mén)了。
https://discuss.leetcode.com/topic/15961/o-1-purely-with-queues
Anyway, Good luck, Richardo! -- 09/11/2016