One, using a single-linked list to implement the stack
① stack requires a stack-top pointer
The basic operations of the ② stack are stack and stack, and determine if the stack is empty
③ each node in a single-linked list represents a stack element, and each node has a pointer to the next node. Therefore, a single linked list needs to be implemented inside the stack. The code is as follows:
Public classStack<textendscomparable<?SuperT>>{ Private classnode{T ele; Node Next; PublicNode (T ele) { This. Ele =Ele; }} Node top;//stack top pointer Public voidpush (T ele) {Node n=NewNode (ele); N.next=top; Top=N; } PublicT Pop () {if(Top! =NULL) {Node tmp=Top.next; T Ele=Top.ele; Top.next=NULL; Top=tmp; returnEle; } return NULL; } Public BooleanIsEmpty () {returntop = =NULL; }}
Two, using two stacks to implement a queue
The ① stack is advanced and out, while the queue is FIFO. To implement the queue, you need to implement the basic operation of the queue, and the basic operation to meet the characteristics of FIFO.
② need two stacks here, one is enstack, and when there are elements in the queue, push to the stack. The other stack is destack when there are elements out of the queue:
First check whether Destack is empty, if not empty, the pop element from Destack out, as the element out of the queue. When Destack is empty, the elements in the enstack are stacked, pushed into the destack, and then out of the destack.
If both Enstack and Destack are empty, the out-of-queue operation returns NULL, and the code is implemented as follows:
Public classMyqueue<textendscomparable<?SuperT>> { PrivateStack<t>Enstack; PrivateStack<t>Destack; PublicMyqueue () {Enstack=NewStack<t>(); Destack=NewStack<t>(); } Public voidEnqueue (T ele) {Enstack.push (ele); } PublicT dequeue () {if(!Destack.isempty ()) { returnDestack.pop (); } while(!Enstack.isempty ()) {Destack.push (Enstack.pop ()); } returnDestack.pop (); } Public BooleanIsEmpty () {returnEnstack.isempty () &&Destack.isempty (); }}
Summary: Whether it is to use the stack to simulate the queue, or to use a queue to simulate the stack, its essence is how a data structure to achieve the characteristics of another data structure.
Implementation of custom stacks and use of two stacks to simulate a queue