順序棧的基本操做實現

1. 順序棧模型示意圖以下:

2. 順序棧結構定義以下:

#define MAXSIZE 10

struct StackNode {
    int data[MAXSIZE];
    int top;
};

3. 順序棧的基本操做函數以下:

  • StackNode* createStack(); // 建立空棧
  • void Push(StackNode* stack, int item); // 入棧
  • int Pop(StackNode* stack); // 出棧,並返回出棧數據
  • int getStackLength(StackNode* stack); // 獲取棧元素個數

4. 具體代碼實現以下:

#include <iostream>

using namespace std;

#define MAXSIZE 10

struct StackNode {
    int data[MAXSIZE];
    int top;
};

StackNode* createStack() {
    StackNode* stack = (StackNode*)malloc(sizeof(StackNode));
    if (stack == NULL) {
        cout << "Memory allocate failed." << endl;
        return NULL;
    }
    for (int i = 0; i < MAXSIZE; i++) {
        stack->data[i] = 0;
    }
    stack->top = -1;
    return stack;
}

void Push(StackNode* stack, int item) {
    if (stack == NULL) {
        cout << "The stack is not created." << endl;
        return;
    }
    if (stack->top == MAXSIZE - 1) {
        cout << "The stack is full." << endl;
        return;
    }
    else {
        stack->data[++(stack->top)] = item;
        return;
    }
}

int Pop(StackNode* stack) {
    if (stack == NULL) {
        cout << "The stack is not created." << endl;
        return 0;
    }
    if (stack->top == -1) {
        cout << "The stack is empty." << endl;
        return 0;
    }
    else {
        return (stack->data[(stack->top)--]);
    }
}

int getStackLength(StackNode* stack) {
    if (stack == NULL) {
        cout << "The stack is not created." << endl;
        return -1;
    }
    return (stack->top + 1);
}

int main() {
    StackNode* stack = NULL;
    stack = createStack();
    Push(stack, 5);
    Push(stack, 4);
    Push(stack, 3);
    cout << "The length of the stack is " << getStackLength(stack) << endl;
    cout << Pop(stack) << endl;
    cout << Pop(stack) << endl;
    cout << Pop(stack) << endl;
    cout << "The length of the stack is " << getStackLength(stack) << endl;
    system("pause");
    return 0;
}

5. 運行結果截圖以下:

相關文章
相關標籤/搜索