【資料結構】 棧

來源:互聯網
上載者:User

標籤:棧   stack   

棧結構,通俗易懂,特點:先進後出,後進先出。

以下,僅對於棧結構常用的操作進行實現

包括:

        入棧(push),出棧(pop),判空(empty),棧頂元素(GetTop)

#include <iostream>using namespace std;template<class T>class Stack{public:    Stack(T size) // 初始化數組大小        :top(0)  //棧頂指標        , _size(size)    {        _array = new T[size]; // top指向最後一個元素時,再往下跳會越界,所以多開一個    }    ~Stack()    {        if (_array)        {            delete[] _array;        }    }public:    void Push(const T val)    {        if (top >= _size)        {            cout << "overflow" << endl;            return;        }        else        {            _array[top] = val;            top++;        }    }    T Pop()    {        T ret;        if (top < 0)        {            cout << "underflow" << endl;            return -1;        }        else        {            top--;            ret = _array[top];        }        return ret;    }    bool isEmpty()    {        return top == 0;    }    T Top()    {        if (!isEmpty())        {            return _array[top - 1];        }        else        {            cout << "error:stack is empty!" << endl;        }    }    void Show()    {        if (isEmpty())        {            cout << "stack has no data!" << endl;            return;        }        for (size_t i = 0; i < top; i++)        {            cout << _array[i] << " ";        }        cout << endl;    }private:    size_t top;    size_t _size;    T* _array;};void Test(){    Stack<int> stk(5);    stk.Push(1);    stk.Push(2);    stk.Push(3);    stk.Push(4);    stk.Push(5);    stk.Show();    cout << stk.Top() << endl;    cout << stk.Pop() << endl;    cout << stk.Pop() << endl;    cout << stk.Pop() << endl;    cout << stk.Top() << endl;    stk.Show();}int main(){    Test();    system("pause");    return 0;}

棧結構是最簡單的資料結構,很多資料結構都會用到棧結構,所以簡單的棧結構常用的操作需掌握。


若有紕漏,歡迎指正

本文出自 “Vs呂小布” 部落格,請務必保留此出處http://survive.blog.51cto.com/10728490/1768289

【資料結構】 棧

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.