当先锋百科网

首页 1 2 3 4 5 6 7

1. 顺序栈

#include <iostream>

using namespace std;

#define MAXSIZE 12
#define OK 1
#define ERROR 0


//顺序栈
typedef struct Sqstack {
	int* top;
	int* base;
	int stacksize;
}Sqstack;


int initSatck(Sqstack& s) {
	//构造一个空栈
	s.base = new int[MAXSIZE];
	if (!s.base) exit(0);
	s.top = s.base;
	s.stacksize = MAXSIZE;
	return OK;
}

int Push(Sqstack& s, int e) {

	if (s.top - s.base == MAXSIZE) return 0;
	*s.top++ = e;
	return OK;
}
int Pop(Sqstack& s, int& e) {

	if (s.top == s.base) return ERROR;
	e = *(--s.top);
	return OK
}

//取栈顶元素值
int getTop(Sqstack& s) {
	if (s.top!=s.base) {
		return *(s.top - 1);
	}
}

void deleteStack(Sqstack &s) {
	delete[] s.base;
	cout << "成功删除";
}

void printStack(Sqstack& s) {

	for (int i = 0; i < 12; i++) {
		cout << s.base[i] << " ";
	}
}

int main() {
	Sqstack s;
	initSatck(s);
	for (int i = 0; i < 12; i++) {
		Push(s, i);
	}
	int flag = Push(s, 13);
	if (flag==0) {
		cout << "栈已满";
	}

	printStack(s);
	deleteStack(s);

	
	return 0;
}

2.链栈


//链栈 以单链表的头结点当栈顶
#include <iostream>

using namespace std;

#define ERROR 0
#define OK    1

typedef struct stackNode {

	int data;
	struct stackNode* next;

}stackNode,*linkStack;

//链栈的初始化
int initStack(linkStack &S) {

	S = NULL;//初始化一个空栈
	return OK;
}

//进栈
int Push(linkStack& S, int e) {

	linkStack p = new stackNode;
	p->data = e;
	p->next = S;

	S = p;//修改栈顶指针为p
	return OK;
}

//出栈
int Pop(linkStack& S, int &e) {

	if (S = NULL) return ERROR;

	e = S->data;
	linkStack p = S;//设置一个临时变量
	S = S->next;
	delete p;//释放节点
	return OK;
}

//取栈顶元素
int getTop(linkStack& S) {

	if (S!=NULL) {
		return S->data;
	}
}