总结归纳
栈的特点是先进后出(First In Last Out / FILO),可以理解为叠罗汉,先来的叠在最下面,要等上面的都抽走了它才能出来。 栈的创建、入栈、出栈、查找,都是在O(1)的时间复杂度内完成。 关于销毁栈,这里使用的是静态数组,所以只需将S.top重置为-1,即为清空栈(逻辑上),新元素的入栈直接覆盖即可。 通过变量声明占用的内存,将在代码结束后由系统自动回收,只有通过 malloc / new 申请的内存空间,才需要手动 free / delete。
代码实现
# define MaxSize 10 # include <cstdlib>
# include <iostream>
# include <string> using namespace std; typedef int ElemType; struct SqStack { ElemType data[ MaxSize] ; int top;
} ;
void InitStack ( SqStack & S) { S. top = - 1 ; }
bool StackEmpty ( SqStack S) { if ( S. top == - 1 ) { return true ; } else { return false ; }
}
bool Push ( SqStack & S, ElemType x) { if ( S. top == MaxSize - 1 ) { return false ; } else { S. top++ ; S. data[ S. top] = x; return true ; }
}
bool Pop ( SqStack & S, ElemType & x) { if ( S. top == - 1 ) { return false ; } else { x = S. data[ S. top-- ] ; return true ; }
}
bool GetTop ( SqStack S, ElemType & x) { if ( S. top == - 1 ) { return false ; } else { x = S. data[ S. top] ; return true ; }
} bool DestroyStack ( SqStack & S) { S. top = - 1 ; } int main ( ) { SqStack S; InitStack ( S) ; cout << "栈是否为空:" << StackEmpty ( S) << endl; for ( int i = 0 ; i < 5 ; i++ ) { Push ( S, i) ; } ElemType top, pop; GetTop ( S, top) ; cout << "栈顶元素:" << top << endl; Pop ( S, pop) ; cout << "出栈元素:" << pop << endl; GetTop ( S, top) ; cout << "新栈顶元素:" << top << endl; DestroyStack ( S) ; cout << "栈是否为空:" << StackEmpty ( S) << endl;
}