stack (C++中STL库常用stack基本用法的实现) ([链表],[数组]的实现)

Stack:依循先进后出原则的单调队列.

下面是用链表实现的stack的几个基本用法和一个clear()的补充用法:

#include
/*
*Date:2018/10/22
*Author:Fushicho
*Name:stack链表版
*Function:push(),pop(),top(),emtpy(),size(),clear()
*/
struct node {
	int num;                    //节点元素
	node *pre_p;                //节点指针指向该节点的前一个节点
	node() {                    //构造函数(初始化)
		this->pre_p = NULL;
	}
};
struct stack {
private:
	node *Top;                  //栈顶指针
public:
	stack() {                   //构造函数(初始化)
		Top = NULL;
	}
	
	void push(int x) {          //向栈顶放入一个元素
		node *p = new node();
		p->num = x;
		if (emtpy()) {          //栈为空
			Top = p;
		}
		else {                  //栈不为空
			p->pre_p = Top;
			Top = p;
		}
	}

	void pop() {                //将栈顶节点弹出并释放内存
		node *p = Top;
		Top = Top->pre_p;
		delete(p);
	}

	int top() {                 //获得栈顶元素
		return Top->num;
	}

	bool emtpy() {              //判断栈是否为空 
		return (Top != NULL) ? false : true;
	}

	int size() {               //计算栈元素个数
		node *p = Top;
		int cnt = 0;
		while (p != NULL) {
			p = p->pre_p;
			cnt++;
		}
		return cnt;
	}

	void clear() {              //清空(需要把每个节点都释放内存,优点:节省内存,缺点:时间慢)
		node *p = Top;
		Top = Top->pre_p;
		while (Top != NULL) {
			delete(p);
			p = Top;
			Top = Top->pre_p;
		}
	}
};

void debug() {          //测试代码
	stack s;
	int a[] = { 1,2,3,4,5,6 };
	printf("入栈顺序:\n");
	for (int i = 0; i < 6; i++) {
		printf("%d ", a[i]);
		s.push(a[i]);
	}
	printf("\n");

	printf("当前栈中元素个数为:%d\n", s.size());

	printf("出栈顺序:\n");
	while (!s.emtpy()) {
		int x = s.top(); s.pop();
		printf("%d ", x);
	}
	printf("\n");
}

int main() {
	debug();
	return 0;
}

下面是用数组实现的stack的几个基本用法和一个clear()的补充用法:

#include
const int maxn = 1e5;
/*
*Date:2018/10/22
*Author:Fushicho
*Name:stack数组版
*Function:push(),pop(),top(),empty(),size(),clear()
*/
struct stack {
private:
	int sta[maxn];
	int Top;
public:
	stack() {            //构造函数(初始化)
		Top = -1;
	}
	
	void push(int x) {   //向栈顶放入一个元素
		sta[++Top] = x;
	}

	void pop() {         //将栈顶弹出
		Top--;
	}

	int top() {          //获得栈顶元素
		return sta[Top];
	}

	bool empty() {       //判断栈是否为空 
		return Top >= 0 ? false : true;
	}

	int size() {         //获得栈中元素个数
		return Top + 1;
	}

	void clear() {       //清空(数组模拟的优点:只需要修改栈顶编号)
		Top = -1;
	}
};

void debug() {          //测试代码
	stack s;
	int a[] = { 1,2,3,4,5,6 };
	printf("入栈顺序:");
	for (int i = 0; i < 6; i++) {
		printf("%d ", a[i]);
		s.push(a[i]);
	}
	printf("\n");

	printf("当前栈中元素个数为:%d\n", s.size());

	printf("出栈顺序:");
	while (!s.empty()) {
		int x = s.top(); s.pop();
		printf("%d ", x);
	}
	printf("\n");
}

int main() {
	debug();
	return 0;
}


若有不懂或者有写错的地方请在下方评论指出,谢谢~

你可能感兴趣的:(数据结构)