【數據結構】順序棧

Stack.h

#pragma once
#include<stdlib.h>
#include<iostream>
using namespace std;
#define SIZE 10
#define Elemtype int
#define StackInit 10

typedef struct Sqstack
{
    Elemtype stack[SIZE];
    int top;
}Sqstack;

void Init(Sqstack* s)
{
    s->top = 0;
}

void Push(Sqstack *s,Elemtype &e)
{
    if (s->top == SIZE)
    {
        cout << "棧已滿,不能插入!" << endl;
        return;
    }

    s->stack[s->top++] = e;
    //++s->top;
    return;
}

bool Empty(Sqstack *s)
{
    return s->top == 0;

}

void Pop(Sqstack *s, Elemtype &e)
{
    if (Empty(s))
    {
        cout << "棧是空的,不能刪除!" << endl;
        return ;
    }
    e = s->stack[--s->top];
    //--s->top;
}

void Gettop(Sqstack *s,Elemtype &e)
{
    if (Empty(s))
        return;
    int temp = s->top;
    e = s->stack[--temp];
    cout << "棧頂元素:" <<e<< endl;
}

void Length(Sqstack *s)
{
    int len = s->top;
    cout << "棧長爲:" << len << endl;
}

void clear(Sqstack *s)
{
    if (Empty(s))
        return;
    s->top = 0;
    cout << "棧已清空!" << endl;
}

void Traverse(Sqstack *s)
{
    if (s->top == SIZE)
        for (int i = 0;i>StackInit; ++i)
        {
            s->stack[s->top] = (Elemtype)malloc(sizeof(Elemtype));
            s->top++;
        }
    //s->stack[s->top]==(Elemtype)malloc(sizeof(Elemtype)*StackInit)

}

main.cpp

#include"Stack.h"
void main()
{
    Sqstack *s;
    Sqstack q;
    Elemtype e;
    s = &q;
    int select = 1;
    while (select)
    {
        cout << "**********************************" << endl;
        cout << "* [1] init        [2] push       *" << endl;
        cout << "* [3] gettop      [4] length     *" << endl;
        cout << "* [5] pop         [6] clear      *" << endl;
        cout << "* [0]quit                        *" << endl;
        cout << "**********************************" << endl;
        cout << "please chose:>";
        cin >> select;
        switch (select)
        {
        case 1:
            Init(s);
            break;
        case 2:
            cout << "請輸入要入棧的數據:";
            cin >> e;
            Push(s, e);
            break;
        case 3:
            Gettop(s, e);
            break;
        case 4:
            Length(s);
            break;
        case 5:
            Pop(s, e);
            cout << "出棧的數據是:" << e << endl;
            break;
        case 6:
            clear(s);
            break;
        case 0:
            cout << "退出成功!" << endl;
            break;
        default:
            break;
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章