Stack related interview questions

Stack related interview questions

Full code: https://github.com/zzaiyuyu/InterviewOfStack

Implement a stack that returns the minimum value of the stack in O(1) time

Use an extra stack to store the minimum value of the current stack.

push: Make a judgment when the data stack is pushed into the element. If the element is less than or equal to the top element of the minimum stack, push both elements into the stack.

pop: When popping elements from the data stack, if the top elements of the two stacks are equal, both stacks will pop out elements, otherwise only the data stack will be popped.

Implement a queue with two stacks

One stack-in element, and one stack-out element.

pop: When popping an element, if it is empty, you need to dump the A element of the stack to the B stack. In addition, consider that both stacks are empty.

Check the correct stacking order

Such as input {1, 2, 3, 4, 5}, output {4, 5, 3, 2, 1}

Two string pointers, in, out.

If out is not equal to the top element of the stack (or the stack is empty), the elements of in are pushed into the stack, and if in is finished, it is in the wrong order.

If out is equal to the top element of the stack, pop the element, out++.

If the out is finished, it is in the correct order.

Implementing two stacks with one array

One top = 0, one top = 1. Each += 2 when pushed onto the stack.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325896931&siteId=291194637