实现链式栈

来源:互联网 发布:淘宝误删宝贝恢复 编辑:程序博客网 时间:2024/05/22 23:21

栈作为一种数据结构,它按照后进先出的原则存储数据,只能在栈顶进行插入和删除操作的特殊线性表。

按照存储方式不同,栈可以分为顺序栈和链式栈。

实现链式栈需要注意:
(1)采用链表存储结构;
(2)不需要预定义内存空间,不存在“链式栈满”这种情况;
(3)解决了顺序栈中没有合理分配内存大小的难题。

以下为具体实现代码, 在vs2010上测试通过:

#include <iostream>#include <math.h>struct node{    int data;    node* next;};class myStack{public:    myStack();    ~myStack();    bool empty();    //用链表实现栈,不存在栈满这种情况    bool getTopElement(int &x);    bool push(int x);    bool pop();    int size();private:    int count;    node* top;};int _tmain(int argc, _TCHAR* argv[]){    myStack sta;    bool flag = sta.empty();//判断栈是否为空    if(flag)    {        for(int i = 0; i < 5; i++)            sta.push(i);//入栈    }    int x;    int nsize;    while(!sta.empty())    {        nsize = sta.size();        sta.getTopElement(x);//x = 4, 访问栈顶元素        sta.pop();//栈顶元素出栈    }    return 0;}myStack::myStack(){    count = 0;    top = NULL;//栈顶指针置空,当元素入栈后,栈顶指针才有具体指向}bool myStack::empty(){    if(count == 0)        return true;    else        return false;}bool myStack::getTopElement(int &x){    if(empty())        return UNDERFLOW;    else    {        x = top->data;        return true;    }}bool myStack::push(int x){    node* p = new node;//新建结构体对象    p->data = x;    p->next = top;//确定p的下一个结点    top = p;//更新栈顶指针的指向    count++;//元素个数增加    return true;}bool myStack::pop()//该函数容易出错{    if(empty())        return UNDERFLOW;//提示范围溢出    else    {        node* temp = new node;        temp = top;//temp指向待删除结点(pop()删除头结点)        top = temp->next;//跳过待删除结点        delete temp;        count--;//减少元素个数        return true;    }}int myStack::size(){    return count;}myStack::~myStack()//逐个释放栈中的元素{    while(!empty())        pop();}
0 0