C++ class实现链栈(完整代码)

Posted Wecccccccc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++ class实现链栈(完整代码)相关的知识,希望对你有一定的参考价值。

代码如下:

#include <iostream>
using namespace std;
typedef int ElemType;

class StackNode {
		friend class LinkStack;
	private:
		ElemType data;
		StackNode *next;
		StackNode(): next(NULL) {
		};
};

class LinkStack {
	public:
		LinkStack(): top(NULL) {
		};
		~LinkStack() {
			StackNode *p;
			while (top) {
				p = top;
				top = top->next;
				delete  p;
			}
			top = NULL;
		};
		int Empty_Stack();
		int Push_Stack(ElemType e);
		int Pop_Stack(ElemType &e);
		int GetTop_Stack(ElemType &e);
	private:
		StackNode *top;
};


int LinkStack::Empty_Stack() {
	return (!top);
}

int LinkStack::Push_Stack(ElemType e) {
	StackNode *p;
	p = new StackNode();
	if (p) {
		p->data = e;
		p->next = top;
		top = p;
		return 1;
	} else
		return 0;
}


int LinkStack::Pop_Stack(ElemType &e) {
	StackNode *p;
	if (top) {
		p = top;
		e = p->data;
		top = top->next;
		delete p;
		return 1;
	} else
		return 0;
}

int LinkStack::GetTop_Stack(ElemType &e) {
	if (top) {
		e = top->data;
		return 1;
	} else
		return 0;
}

int main() {
	LinkStack s;
	s.Push_Stack(23);
	s.Push_Stack(12);
	s.Push_Stack(89);
	int x;
	s.Pop_Stack(x);
	cout << x << endl;
	s.GetTop_Stack(x);
	cout << x << endl;
	return 0;
}

测试结果:
在这里插入图片描述

以上是关于C++ class实现链栈(完整代码)的主要内容,如果未能解决你的问题,请参考以下文章

C++ class实现链队列(完整代码)

C++ class实现顺序栈(完整代码)

C++ class实现顺序队列(完整代码)

C++ class实现单链表(完整代码)

C++ class实现邻接矩阵存储的图(完整代码)

C++ class实现Huffman树(完整代码)