Stack
1. Definition: a stack is a linear table that can only be inserted or deleted at the end of the table. Therefore, for the stack, the end of the table has its special meaning, which is called the top of the stack,
The header end is called the bottom of the stack. Empty tables without elements are called empty stacks.
Suppose stack S=(a1,a2,a3,...,an), then we call a1 the bottom element and an the top element. The elements in the stack are pushed in the order of a1,a2,a3,...,an, and the first one is pushed back
An element should be the top of stack element. In other words, the stack is modified on a last in, first out basis. So the stack is also called the last in first out linear table. So data structure
For:
#define STACK_INIT_SIZE 100 struct BinTreeNode; struct StkNode; typedef enum {L, R}Tag; typedef struct StkNode { struct BinTreeNode *ptr; Tag tag; }StkNode; #ifdef PREORIN #define ElemTypeStack BinTreeNode* #else #define ElemTypeStack StkNode #endif typedef struct Stack { ElemTypeStack *base; size_t capacity; int top; }Stack;
2. Therefore, there are the following operations in the stack:
bool IsFull(Stack *st); bool IsEmpty(Stack *st); void InitStack(Stack *st, int sz); void PushStack(Stack *st, ElemTypeStack x); void ShowStack(Stack *st); void PopStack(Stack *st); ElemTypeStack GetTop(Stack *st); void ClearStack(Stack *st);
The above methods are as follows: (1) judge whether the stack is full; (2) judge whether the stack is empty; (3) initialize a stack operation; (4) move to the stack
Push in elements. (5) display the contents of the stack. (6) delete the elements in the stack. (7) get the top elements of the stack. (8) clear the stack
3. Implement the method declared above:
bool IsFull(Stack *st) { return st->top >= st->capacity; } bool IsEmpty(Stack *st) { return st->top == 0; } void InitStack(Stack *st, int sz=STACK_INIT_SIZE) { st->capacity = sz > STACK_INIT_SIZE ? sz : STACK_INIT_SIZE; st->base = (ElemTypeStack*)malloc(sizeof(ElemTypeStack)*st->capacity); assert(st->base != NULL); st->top = 0; } void PushStack(Stack *st, ElemTypeStack x) { if(IsFull(st)) { cout<<"The stack is full.,"<<x<<"Unable to stack."<<endl; return; } st->base[st->top++] = x; } void ShowStack(Stack *st) { for(int i=STACK_INIT_SIZE-1; i>=0; --i) { cout<<i<<" : "; if(i >= st->top) cout<<"Nul."<<endl; else cout<<st->base[i]<<"."<<endl; } } void PopStack(Stack *st) { if(IsEmpty(st)) { cout<<"The stack is empty.,Unable to stack."<<endl; return; } st->top--; } ElemTypeStack GetTop(Stack *st) { assert(!IsEmpty(st)); return st->base[st->top-1]; } void ClearStack(Stack *st) { st->top = 0; }