Bootstrap

数据结构:栈

栈分为顺序栈和链栈,它的操作包括初始化栈,入栈,出栈,销毁栈,获取栈长,获取栈顶元素,打印栈等。

顺序栈结构体创建:

typedef struct sqStack {
	int data[maxSize];
	int top;

}sqStack;

初始化栈:

void initStack(sqStack&S){
	S.top = -1;
}

入栈:

void push(sqStack&S,int num){
	if (S.top == maxSize - 1) {
		cout << "Stack is full" << endl;
		return;
	}
	S.top++;
	S.data[S.top] = num;
}

出栈:

void pop(sqStack&S){
	if (S.top == -1) {
		cout << "Stack is empty" << endl;
		return;
	}
	S.top--;
}

判空:

bool isEmpty(sqStack&S) {
	if (S.top == -1) {
		return 1;
	}return 0;
}

获取栈长:

int getLen(sqStack&S){
	return S.top + 1;
}

 获取栈顶:

int getTop(sqStack&S){
	if (S.top == -1) {
		cout << "NO top element" << endl;
		return -1;
	}
	return S.data[S.top];

}

 打印栈:

void printStack(sqStack&S) {
	int m = S.top;//不直接对S.top进行操作方便之后运算
	while (m!= -1) {
		cout << S.data[m--] << " ";
	}
	cout << endl;
}

销毁栈:

void destroyStack(sqStack&S){
	S.top = -1;
}

完整代码如下:

#include<iostream>
using namespace std;
#define maxSize 100
typedef struct sqStack {
	int data[maxSize];
	int top;

}sqStack;
void initStack(sqStack&S){
	S.top = -1;
}
bool isEmpty(sqStack&S) {
	if (S.top == -1) {
		return 1;
	}return 0;
}
int getLen(sqStack&S){
	return S.top + 1;
}
void push(sqStack&S,int num){
	if (S.top == maxSize - 1) {
		cout << "Stack is full" << endl;
		return;
	}
	S.top++;
	S.data[S.top] = num;
}
void pop(sqStack&S){
	if (S.top == -1) {
		cout << "Stack is empty" << endl;
		return;
	}
	S.top--;
}
int getTop(sqStack&S){
	if (S.top == -1) {
		cout << "NO top element" << endl;
		return -1;
	}
	return S.data[S.top];

}

void destroyStack(sqStack&S){
	S.top = -1;
}
void printStack(sqStack&S) {
	int m = S.top;
	while (m!= -1) {
		cout << S.data[m--] << " ";
	}
	cout << endl;
}
int main() {
	sqStack S;
	initStack(S);
	int n;
	int m = 5;
	while (m--) {
		cin >> n;
		push(S, n);
	}
	cout << getLen(S) << endl;
	printStack(S);
	cout << getTop(S) << endl;
	pop(S);
	printStack(S);
	destroyStack(S);
	return 0;
}

运行结果:

这是顺序栈的一些基本操作,对于链栈,则构造以下结构体:

typedef struct node {
	int data; 
	struct node* next; 
}listStack; 

其他的操作基本就是链表那套了

;