題目要求:用兩個棧來實現(xiàn)一個隊列,完成隊列的Push和Pop操作。 隊列中的元素為int類型
眾所周知,棧使一種后進先出的數(shù)據(jù)結(jié)構(gòu),而隊列是一種先進先出的數(shù)據(jù)結(jié)構(gòu),剛好題目要求用兩個棧來實現(xiàn),我們來想想,當(dāng)push的時候,把記錄全部push到stack1中,當(dāng)要pop的時候,我們先把stack1中的所有記錄pop出來,然后再push到stack2中,這樣stack2中最上面的那條記錄不就是之前最先進入棧的么,然后把它pop出來就萬事大吉嘛。當(dāng)然pop出來之后不要忘記把剩下的數(shù)據(jù)重新push回到stack1中。
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
while(!(stack1.empty())){
stack2.push(stack1.pop());
}
int value = stack2.pop();
while(!(stack2.empty())){
stack1.push(stack2.pop());
}
return value;
}
}