数据结构学习---堆栈的动态数组实现及链表实现

来源:互联网 发布:软件测试方法分类 编辑:程序博客网 时间:2024/06/11 06:31

堆栈

【链表实现堆栈】

优点:可以无限增添元素,只要内存足够,

缺点:内存中存储位置不连续

typedef int ElementType;//只能向头部插入元素,因为如果在尾部插入,删除时,找不到上一个节点///因为链表是单向的//所以 push pop 操作在头结点进行class Stack{public:Stack(){S=(Stack*)malloc(sizeof(Stack)); //建立一个不存数据的头结点,方便增删节点S->Next=NULL;sz=0;}bool empty(){return (S->Next==NULL);}int size(){return sz;}void push(ElementType X){Stack* TmpCell=(Stack*)malloc(sizeof(Stack));TmpCell->Date=X;TmpCell->Next=S->Next;  //在头部增添节点S->Next=TmpCell;sz++;}ElementType pop(){Stack* FirstCell; //因为只是用了指向头结点,所以并不需要分配空间ElementType TopElem;if(empty()){cout<<"堆栈空"<<endl; return -1;}else{sz--;FirstCell=S->Next;TopElem=FirstCell->Date;S->Next=FirstCell->Next;free(FirstCell); //释放内存return TopElem;}}private:int Date;Stack* Next;Stack* S;int sz;//记录栈中元素个数}stack;


【动态数组实现堆栈】


好处:申请了连续的内存空间,而且可以无限增添元素(内存足够)


初始化用malloc函数为动态数组分配maxn个空间,

s=(ElementType*)malloc(maxn*sizeof(ElementType));


如果数组满了,用realloc函数,重新分配空间,多分配一个maxn;

 if(Top+1>=maxn*N){ //如果当前栈中元素总量已满, 则重新申请空间,增加maxn个空间      N++;      s=(ElementType*)realloc(s,N*maxn*sizeof(ElementType)); }


整体代码

const int maxn = 10;typedef int ElementType;class Stack{    public:        Stack(){            s=(ElementType*)malloc(maxn*sizeof(ElementType));            Top=-1; //因为希望元素从下标0开始储存,将Top置为-1            N=1;        }        bool empty(){            return (Top==-1);        }        int size(){            return Top+1;        }        void push(ElementType X){            if(Top+1>=maxn*N){ //如果当前栈中元素总量已满, 则重新申请空间,增加maxn个空间                N++;                s=(ElementType*)realloc(s,N*maxn*sizeof(ElementType));            }            s[++Top]=X;        }        ElementType pop(){            if(empty()){                cout<<"堆栈空"<<endl; return -1;            }            else {                return s[Top--];            }            }    private:        int Top; //记录栈顶位置        int Date;         int N;  //记录申请了几倍的maxn        ElementType* s;}stack;


1 0