[数据结构]--链栈的实现

#include <iostream>
using namespace std;

typedef struct StackNode {
	int data;
	struct StackNode *next;
}StackNode, *LinkStack;

// 初始化
bool initStack(LinkStack &S) {
	S = NULL;
	return true;
}

// 销毁
bool destroyStack(LinkStack &S) {
	LinkStack p = S;
	while (p) {
		LinkStack t = p;
		p = p->next;
		delete t;
	}
	S = NULL;
	return true;
}

// 栈空
bool isEmpty(LinkStack S) {
	if (S == NULL) {
		return true;
	} else {
		return false;
	}
}

// 入栈
bool push(LinkStack &S, int e) {
	LinkStack p = new StackNode;
	if (!p) { // 空间分配失败
		return false; 
	}
	p->data = e;
	p->next = S; // 入栈,插在表头
	S = p; // 修改栈顶指针
	return true;
}

// 出栈
bool pop(LinkStack &S, int &e) {
	if (isEmpty(S)) { // 栈空
		return false;
	}
	e = S->data;
	LinkStack p = S; // 保存栈顶元素
	S = S->next; // 修改栈顶指针
	delete p;
	return true;
}

// 取栈顶
int getTop(LinkStack S) {
	if (S != NULL) {
		return S->data;
	}
	return -1;
}

int main(int argc, char const *argv[])
{
	LinkStack S;
	initStack(S);
	if (isEmpty(S)) {
		cout << "栈为空" << endl;
	}

	for (int i = 1 ;i <= 10; ++i) {
		push(S, i);
		cout << "栈顶元素为:" << getTop(S) << endl;
	}

	for (int i = 1; i <= 5; ++i) {
		int e;
		if (pop(S, e)) {
			cout << "出栈元素:" << e << endl;
		}
	}

	destroyStack(S);
	if (isEmpty(S)) {
		cout << "栈销毁" << endl;
	}

	return 0;
}
上一篇:条件控制


下一篇:c++练习10——两个栈实现一个队列