The stack implements the last-in-first-out (advanced-out) strategy, and the queue implements the FIFO strategy.
1 Stacks
the operations on the stack mainly include
- The insert operation is called Press-in (push). Note the overflow problem, which is to add elements to the full stack.
- A delete operation with no parameter version is called eject (pop). Note the underflow problem, which is to take the element from the empty stack.
- Stack-empty to determine if the stack is empty
the idea of the stack implementation
Use an array of S[1..N] to implement a stack that accommodates up to n elements. The array has a parameter s.top to indicate where to insert the element, S[0] is the bottom of the stack, and S[s.top-1] is the top of the stack.
Pseudo code
1. Determine if the stack is empty:
empty()if0 returntrueelse returnfalse
2. Insert Push
if top > size error"upflow"else stack[top] =x; top=top+1
3. Delete Pop
if empty() "underflow"else poppop-1 return stack[pop]
Template implementation of the stack
#include <iostream>Template<classTConst intSize = ->classstack{T S[size];intTop Public: Stack (): Top (0){}BOOLEmpty () {returntop = =0;} T Pop () {if(Top <=0){STD::Cerr<<"Underflow";Exit(0); }returnS[--top]; }voidPush (T t) {if(Top >= size) {STD::Cerr<<"Overflow";Exit(0); } s[top++] = t; }};//test codeintMain () {Const intSize =Ten; stack<int, size> si; for(inti =0; i < size; i++) {STD::cout<< i; Si.push (i); }STD::cout<<STD:: Endl; while(!si.empty ())STD::cout<< Si.pop ();}
Implement two stacks in an array so that when the sum of the two stack elements is not n, it will not overflow. Push and pop operations run at O (1)
To have 2 stacks common one storage space, the stack top pointer starts from both ends, and overflows when the two pointers point to the same memory.
#include <iostream>Template<classTConst intSize = ->classstack{T S[size];intTOP1;intTOP2; Public: Stack (): Top1 (0), TOP2 (size-1){}BOOLEmptyintIndex) {if(Index = =1)returnTOP1 = =0;Else returnTOP2 = = size-1; } T POPs (intIndex) {if(Index = =1&& TOP1 = =0){STD::Cerr<<"Underflow";Exit(0); }if(Index = =2&& TOP2 = = size-1){STD::Cerr<<"Underflow";Exit(0); }if(Index = =1)returnS[--TOP1];Else returnS[++TOP2]; }voidPush (T T,intIndex) {if(Top1 = = TOP2) {STD::Cerr<<"Overflow";Exit(0); }if(Index = =1) s[top1++] = t;Elses[top2--] = t; }};intMain () {Const intSize =Ten; stack<int, size> si; for(inti =0; I <4; i++) {STD::cout<< i; Si.push (I,1); }STD::cout<<STD:: Endl; for(inti =0; I <5; i++) {STD::cout<< i; Si.push (I,2); }STD::cout<<STD:: Endl; while(!si.empty (1))STD::cout<< Si.pop (1);STD::cout<<STD:: Endl; while(!si.empty (2))STD::cout<< Si.pop (2);}
1 Stack-oop