admin管理员组文章数量:1636954
We are given a Queue data structure that supports standard operations like enqueue() and dequeue(). We need to implement a Stack data structure using only instances of Queue
this question is from GeeksforGeeks
Implement Stack Question from geeksforgeeks
此问题和 Implement Queue use Stack 一样
两种方法实现:
1 update on each push operation
push(s, x) // x is the element to be pushed and s is stack
1) Enqueue x to q2
2) One by one dequeue everything from q1 and enqueue to q2.
3) Swap the names of q1 and q2
// Swapping of names is done to avoid one more movement of all elements
// from q2 to q1.
pop(s)
1) Dequeue an item from q1 and return it.
2 Update when pop --很好理解,就是把queue1中除了最后一个都存到queue2中,poll出queue1中最后一个就是latest element,交换名字
In push operation, the new element is always enqueued to q1.
In pop() operation, if q2 is empty then all the elements except the last, are moved to q2.
Finally the last element is dequeued from q1 and returned.
push(s, x)
1) Enqueue x to q1 (assuming size of q1 is unlimited).
pop(s)
1) One by one dequeue everything except the last element from q1 and enqueue to q2.
2) Dequeue the last item of q1, the dequeued item is result, store it.
3) Swap the names of q1 and q2
4) Return the item stored in step 2.
// Swapping of names is done to avoid one more movement of all elements from q2 to q1.
private Queue<Integer> queue1;
private Queue<Integer> queue2;
public ImplementStackusingQueues() {
// do initialization if necessary
queue1 = new LinkedList<Integer>();
queue2 = new LinkedList<Integer>();
}
public void push(int element){
queue1.offer(element);
}
public int pop(){
while(queue1.size() > 1){
queue2.offer(queue1.poll());
}
//remain last element
int top = queue1.poll();
queue1 = queue2;
queue2 = queue1;
return top;
}
版权声明:本文标题:Implement Stack Using Queue 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/xitong/1729235330a1191926.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论