順序棧的基本操作實現


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. 運行結果截圖如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM