數據結構之棧

#include <iostream>

using namespace std;

#define STACKMAXSIZE 100
struct Stack//基於數組實現棧,也可以基於單向鏈表實現
{
    int data[STACKMAXSIZE];
    int top;
};


bool CreateEmptyStack(Stack& stack);//置空棧
bool IsEmpty(Stack& stack);//判斷棧是否爲空
bool PushStack(Stack& stack, int value);//進棧
bool PopStack(Stack& stack);//出棧
int GetTopElement(Stack& stack);//取棧頂元素,不改變棧本身
bool PrintStack(Stack& stack);//顯示整個棧


int main()
{
    Stack s;

    CreateEmptyStack(s);
    if (IsEmpty(s)) cout << "Stack is empty!" << endl;

    PushStack(s, 0);
    PushStack(s, 1);
    PushStack(s, 2);
    PushStack(s, 3);
    PushStack(s, 4);
    if (!IsEmpty(s)) PrintStack(s);
    cout << endl;

    int result = 0xFFFFFFF;
    result = GetTopElement(s);
    if (result != 0xFFFFFFF) cout << result << endl;

    PopStack(s);
    if (!IsEmpty(s)) PrintStack(s);
    cout << endl;
    PopStack(s);
    if (!IsEmpty(s)) PrintStack(s);
    cout << endl;
    PopStack(s);
    if (!IsEmpty(s)) PrintStack(s);
    cout << endl;
    PopStack(s);
    if (!IsEmpty(s)) PrintStack(s);
    cout << endl;
    PopStack(s);
    if (!IsEmpty(s)) PrintStack(s);
    cout << endl;
    PopStack(s);
    if (!IsEmpty(s)) PrintStack(s);
    cout << endl;


    system("pause");
    return 0;
}

bool CreateEmptyStack(Stack& stack)
{
    stack.top = -1;
    return true;
}

bool IsEmpty(Stack& stack)
{
    if (stack.top < 0) return true;
    else return false;
}

bool PushStack(Stack& stack, int value)
{
    if (stack.top >= STACKMAXSIZE - 1)
    {
        cout << "Stack is full,can't push element into it!" << endl;
        return false;
    }
    stack.data[stack.top + 1] = value;
    stack.top += 1;

    return true;
}

bool PopStack(Stack& stack)
{
    if (stack.top < 0)
    {
        cout << "Stack is empty,can't pop element from it!" << endl;
        return false;
    }

    stack.top -= 1;
    return true;
}

int GetTopElement(Stack& stack)
{
    if (IsEmpty(stack))
    {
        cout << "Stack is empty,can't get its top!" << endl;
        return -1;
    }
    else return stack.data[stack.top];
}

bool PrintStack(Stack& stack)
{
    if (IsEmpty(stack))
    {
        cout << "Stack is empty,can't print it!" << endl;
        return false;
    }

    for (int i = 0; i <= stack.top; ++i)
        cout << stack.data[i] << " ";
    return true;
}








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章