wupangyen / LeetCode

LeetCode
1 stars 0 forks source link

LeetCode.225 Implement Stack using Queues #9

Open wupangyen opened 3 years ago

wupangyen commented 3 years ago

Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).

Implement the MyStack class:

void push(int x) Pushes element x to the top of the stack. int pop() Removes the element on the top of the stack and returns it. int top() Returns the element on the top of the stack. boolean empty() Returns true if the stack is empty, false otherwise. Notes:

You must use only standard operations of a queue, which means that only push to back, peek/pop from front, size and is empty operations are valid. Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations.

wupangyen commented 3 years ago

Example 1:

Input ["MyStack", "push", "push", "top", "pop", "empty"] [[], [1], [2], [], [], []] Output [null, null, null, 2, 2, false]

Explanation MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False

wupangyen commented 3 years ago

we can implement a queue using linked list

for push operation:

stack is first in last out

queue is first in first out

// lets say we want to push 0, 1, 2

first we push to queue 0 second when we push 1 to queue 0,1 but this is not the order we want for stack we want 1, 0 for stack so we rotate them for(int i = 1 i < queue.size ; i ++){ queue.add(queue.remove) }

pop we use queue.remove

top we use queue.peek

empty we use queue.isEmpty()

wupangyen commented 3 years ago

class MyStack { Queue q;

/** Initialize your data structure here. */
public MyStack() {
    q = new LinkedList<Integer>();
}

/** Push element x onto stack. */
public void push(int x) {
    q.add(x);
    for(int i = 1; i < q.size(); i ++){
        q.add(q.remove());
    }
}

/** Removes the element on top of the stack and returns that element. */
public int pop() {

    return q.remove();

}

/** Get the top element. */
public int top() {
    return q.peek();
}

/** Returns whether the stack is empty. */
public boolean empty() {
    return q.isEmpty();
}

}

/**