1. 程式人生 > >棧的順序結構及棧的實現

棧的順序結構及棧的實現

棧是線性表的一種特例,其後進先出的資料結構在開發中比較常見。許多軟體、應用都提供撤銷的操作(ctrl+z),其實現原理就是使用了棧的資料結構。

棧是限定僅在表尾進行插入和刪除操作的線性表。
通常把允許插入和刪除的一端稱為棧頂(top),另外一端稱為棧底(bottom),不辦含任何資料元素的棧稱之為空棧。棧又稱之為後進先出的線性表,簡稱LIFO結構。
既然棧屬於線性表,那麼棧元素之間就具有線性關係,即前驅後繼關係。常用的棧操作方式有:入棧(push)和出棧(pop)

定義棧的資料結構

struct Stack{
    int data[MAXSIZE];
    int top;
}myStack;

入棧操作:

void push(Stack *s,int element){
    if (s->top==MAXSIZE){
        cout<<"棧滿"<<endl;
        return;
    }
    s->data[s->top]=element;
    cout<<s->data[S-top]<<endl;
    s->top++;
}

出棧操作:

int pop(Stack *s)
{
    int e;
    while (s->top <= 0)
    {
        cout <<
"棧空" << endl; return false; } s->top--; e = s->data[s->top]; return e; }

測試程式碼如下:

int main()
{
    int n;
    cout << "請輸入入棧的元素個數,最大為10" << endl;
    cin >> n;
    cout << "入棧" << endl;
    for (auto i = 0; i < n; i++)
    {
        push(&myStack, i);
    }
    cout
<< "---分隔符---出棧" << endl; cout << "出棧" << endl; int n1; cout<<"請輸入要出棧的元素的個數"<<endl; cin>>n1; for (auto i = 0; i < n1; i++) { cout<< pop(&myStack)<<endl; } /* cout << "---分隔符---出棧" << endl; while (true) { int n2; cout << "請輸入要出棧的元素的個數" << endl; cin >> n2; for (auto i = 0; i < n2; i++) { pop(&myStack); } } */ return 0; }

輸出如下圖所示:

輸出

歡迎關注公眾號,不定期分享Unity3D、C#、C++資料結構和演算法學習知識。

碼碼小蟲