数据结构——栈

     栈(stack)是一种常用的重要数据结构,由于其具有后进先出(last in first out,LIFO)的特性,又被叫做后进先出线性表。

  基本术语:

   栈顶(top):栈中允许插入和删除的一端叫做栈顶。

   栈底(bottom):不允许插入和删除的另一端。

   入栈/压栈:指向栈中添加元素的操作。

     出栈/弹栈:指删除栈顶元素的操作

  栈的主要操作有:

    (1)初始化     (2)入栈      (3)出栈             (4)栈清空      (5)判断栈是否已满

  常用存储方式:

    1.顺序存储方式  2.链式存储方式

 

顺序栈 

   顺序栈(sseqential stack)是指用顺序存储方式存储的栈,绝大多数情况下是用数组来进行存储。这种存储方式会由一个maxsize,即栈最大允许存放元素的个数。

   这种存储方式相对简单,实现起来很方便。

   一个顺序栈类中包含了三个属性,分别为:1.栈顶指针(常常为数组下标)  2.栈数组(即存放栈中元素的数组)  3.栈最大允许容纳元素个数

   当然顺序栈也可以不限制栈的元素,每次栈中元素溢出时只要重新分配数组内存大小就可以了

   类似的代码如下:

  

顺序栈的实现
 1 /* stack.h
2 **顺序栈实现
3 **编译环境:VS2010,WindowsXP SP3
4 **
5 */
6 #include<iostream>
7 using namespace std;
8 #define REALLOCSIZE 10 /*重新分配内存大小*/
9 template<class type> class stack{
10 public:
11 stack();
12 ~stack(void){free(_arr);}
13 void push(const type& item);  /*入栈操作*/
14 type pop(void); /*出栈操作,返回弹出值*/
15 type top(void); /*返回栈顶元素*/
16 bool empty()const; /*判断栈是否为空*/
17 void clear(void); /*清空栈操作*/
18 private:
19 type* _arr; /*栈内存空间*/
20 int _top; /*栈顶指针*/
21 int _currentsize; /*当前栈内存大小*/
22 };
23
24 /****************具体实现**********************/
25
26 template<class type>
27 stack<type>::stack(){
28 _top=-1;
29 _currentsize=REALLOCSIZE;
30 _arr=(type*)malloc(REALLOCSIZE*sizeof(type));
31 }
32
33 template<class type>
34 void stack<type>::push(const type& item){
35 if(this->_top+1<this->_currentsize){
36 _arr[++_top]=item;
37 }
38 else{
39 this->_currentsize+=REALLOCSIZE;
40 _arr=(type*)realloc(_arr,this->_currentsize*sizeof(type));
41 _arr[++_top]=item;
42 }
43 }
44
45 template<class type>
46 type stack<type>::pop(){
47 if(this->_top>-1){
48 return _arr[this->_top--];
49 }
50 else{
51 cerr<<"ERR!";
52 exit(1);
53 }
54 }
55
56 template<class type>
57 type stack<type>::top(){
58 if(this->_top>-1){
59 return _arr[this->_top];
60 }
61 else{
62 cerr<<"ERR!";
63 exit(1);
64 }
65 }
66
67 template<class type>
68 bool stack<type>::empty()const{
69 return this->_top==-1;
70 }
71
72 template<class type>
73 void stack<type>::clear(){
74 this->_currentsize=REALLOCSIZE;
75 this->_arr=(type*)realloc(_arr,REALLOCSIZE*sizeof(type));
76 this->_top=-1;
77 }

顺序栈的存储方式实现起来简单,但是带来的问题就是栈的大小固定,利用的效率会很低往往浪费很大的内存。

即使采用动态分配数组内存的方式,存储效率也是一个问题。

 

链式栈

  用链式存储方式存储的栈叫做链式栈(linked stack),它很好得弥补了顺序栈的不足之处。

   具体存储方式如下图:

 代码就懒得写了,给个类图吧……

总得来说,栈还是比较简单的一种存储结构,但用途却很广泛。例如:中缀表达式转后缀表达式、编译原理中词法分析、语法分析都大量用到了栈。

 

前段时间人间蒸发,现在强势回归,估计接下来的一个学期会写好多的文章ORZ

posted @ 2011-08-23 23:14  Hazi  阅读(1599)  评论(0编辑  收藏  举报