Likou brush questions--stack implementation queue

stack implements queue

topic:

Use two stacks to implement a queue, and complete the Push and Pop operations of the queue. The elements in the queue are of type int.

Problem-solving ideas:

analyze

The characteristic of the queue is: "first in, first out", and the characteristic of the stack is: "first in, first out"

When we insert the numbers a, b, and c into the simulated queue, assuming that the insertion is stack1, the stack situation at this time is:

  • Stack stack1: {a,b,c}
  • stack stack2: {}

When a number needs to be popped, according to the "first in first out" principle of the queue, a enters first, then a should be popped first. But at this time a is at the bottom of stack1, and all the elements in stack1 are popped and pushed into stack2 one by one. Now a can be correctly popped from stack2. The stack situation at this time is:

  • stack stack1: {}
  • Stack stack2: {c,b}

Continue to pop up a number, b enters the "queue" before c, and b pops up. Note that b is at the top of stack2 and can be popped up directly. The stack situation at this time is:

  • stack stack1: {}
  • Stack stack2: {c}

At this time, insert a number d into the simulation queue, or insert stack1, and the stack situation at this time is:

  • stack stack1: {d}
  • Stack stack2: {c}

Pop a number, c enters before d, and c pops out. Note that c is at the top of stack2 and can be popped directly. The stack situation at this time is:

  • stack stack1: {d}
  • Stack stack2: {c}

From the above chestnuts it can be concluded that:

  1. When inserting, insert directly into stack1
  2. When popping up, when stack2 is not empty, pop the top element of stack2, if stack2 is empty, pop all the numbers in stack1 into stack2 one by one, and then pop the top element of stack2

the complexity:

Time complexity of push: O(1)

Space complexity of pop: O(1)

The specific code is implemented as follows:

import java.util.Stack;

public class Solution {
	Stack<Integer> stack1 = new Stack<Integer>();
	Stack<Integer> stack2 = new Stack<Integer>();
	public void push(int node) {
		while(stack2.size() != 0){
			stack1.push(stack2.pop());
		}
		stack1.push(node);
	}
	public int pop() {
		int node;
		if(stack2.size() != 0){
			node = stack2.pop();
		} else{
			while(stack1.size() != 0){
				stack2.push(stack1.pop());
			}
			node = stack2.pop();
		}
		return node;
	}
}

Guess you like

Origin blog.csdn.net/xiri_/article/details/118700811