Algorithm: Use two stacks to implement a queue, complete the queue push and pop operations. The elements in the queue are of type int. "The sword means offer"
The use of the stack to operate, code comments written more clearly: first determine whether the two stack is empty: Second, when the stack is empty, the stack 1 is taken out to stack two, and finally return to the stack two the first value;
The Pop () method and the push method are used mainly:
Package Lg.nowcoder;/** * @Author Liguo * @Description use two stacks to implement a queue to complete the push and pop operations of the queue. The elements in the queue are of type int. * @Data 2018-08-11 21:50*/import Java.util.Stack; Public classSolution1 {Stack<Integer> Stack1 =NewStack <Integer>(); Stack<Integer> Stack2 =NewStack <Integer>(); Public voidPushintnode) {Stack1.push (node); // directly into the stack } Public intpop () {if(Stack1.empty () && stack2.empty ()) { // judgment stack is empty Throw NewRuntimeException ("Empty linked list" ); } if(Stack2.empty ()) { // when the second stack is non-empty, copy the first stack to the second stack while(!Stack1.empty ()) {Stack2.push (Stack1.pop ()); } } returnStack2.pop (); // return to the second top of the stack }}
Algorithm: Use two stacks to implement a queue, complete the queue push and pop operations. The elements in the queue are of type int. "The sword means offer"