Implement Stack using Queues Leetcode

用队列实现栈
本文介绍了两种使用队列实现栈的方法。一种使用两个队列,通过不断转移元素来模拟栈的后进先出特性;另一种仅用一个队列,通过在插入元素后重新组织队列顺序来保持栈的特性。

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.

Notes:

  • You must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, and is empty operations are valid.
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

 

这道题可以用一个queue实现,我却用了两个。。。两个queue的思路就是一个queue里面放顶点,另一个queue里面按照stack顺序存储。

代码写的很长。。。

public class MyStack {
    Queue<Integer> q1;
    Queue<Integer> q2;
    boolean isQ1;

    /** Initialize your data structure here. */
    public MyStack() {
        q1 = new LinkedList<>();
        q2 = new LinkedList<>();
        isQ1 = true;
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        if (q1.isEmpty()) {
            q1.offer(x);
            isQ1 = true;
        } else if (q2.isEmpty()) {
            q2.offer(x);
            isQ1 = false;
        } else if (isQ1) {
            while (!q2.isEmpty()) {
                q1.offer(q2.poll());
            }
            q2.offer(x);
            isQ1 = false;
        } else {
            while (!q1.isEmpty()) {
                q2.offer(q1.poll());
            }
            q1.offer(x);
            isQ1 = true;
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        int x = 0;
        if (isQ1) {
            x = q1.poll();
            if (!q2.isEmpty()) {
                q1.offer(q2.poll());
            }
        } else {
            x = q2.poll();
            if (!q1.isEmpty()) {
                q2.offer(q1.poll());
            }
        }
        return x;
    }
    
    /** Get the top element. */
    public int top() {
        if (isQ1) {
            return q1.peek();
        }
        return q2.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        if (q1.size() == 0 && q2.size() == 0) {
            return true;
        }
        return false;
    }
}

/**
 * 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();
 */

 

一个queue的思路就是每次enqueue, dequeue。

public class MyStack {
    Queue<Integer> q;

    /** Initialize your data structure here. */
    public MyStack() {
        q = new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        q.offer(x);
        for (int i = 0; i < q.size() - 1; i++) {
            q.offer(q.poll());
        }
    }
    
    /** 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();
 */

这个算法果然跑得很快。。。只有push的时候是O(n)。因为push的时候就是按照stack的顺序push进去的。

转载于:https://www.cnblogs.com/aprilyang/p/6385560.html

在实现队列(Queue)的数据结构时,可以使用链表(Linked Lists)和数组(Arrays)这两种常见的数据结构。 a. 使用链接列表(Linked List)实现队列: ```python class Node: def __init__(self, data): self.data = data self.next = None class QueueLL: def __init__(self): self.head = None self.tail = None # 入队操作(enqueue) def enqueue(self, data): new_node = Node(data) if not self.is_empty(): self.tail.next = new_node else: self.head = new_node self.tail = new_node # 出队操作(dequeue) def dequeue(self): if self.is_empty(): return None temp_data = self.head.data self.head = self.head.next if self.is_empty(): self.tail = None return temp_data # 检查队列是否为空 def is_empty(self): return self.head is None # 显示队列元素 def display(self): current = self.head while current: print(current.data, end=" -> ") current = current.next print("None") ``` b. 使用数组实现队列(Array-Based Queue): ```python class QueueArray: def __init__(self, capacity): self.queue = [None] * capacity self.front = -1 self.rear = -1 def is_empty(self): return self.front == self.rear def enqueue(self, data): if (self.rear + 1) % len(self.queue) == self.front: raise Exception("Queue full") if self.is_empty(): self.front = self.rear = 0 else: self.rear = (self.rear + 1) % len(self.queue) self.queue[self.rear] = data def dequeue(self): if self.is_empty(): raise Exception("Queue empty") value = self.queue[self.front] if self.front == self.rear: self.front = self.rear = -1 else: self.front = (self.front + 1) % len(self.queue) return value def display(self): if self.is_empty(): print("Queue is empty") else: index = self.front while True: try: print(self.queue[index], end=" -> ") index = (index + 1) % len(self.queue) except IndexError: break print("None") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值