C++重写单链表实现的栈

#include<iostream>
#include<assert.h>
#include<string.h>
typedef int ElemType;
using namespace std;

typedef struct StackNode
{
	ElemType data;
	StackNode *next;
}SNode;

class CLinkStack
{
public:CLinkStack();
	   ~CLinkStack();
	   void StackClear()		//清空栈
	   {
		   SNode *p = this->_buttom;
		   while (p!=NULL)
		   {
			   delete p;
			   p = p->next;
		   }
		   this->_buttom = this->_top = NULL;
		   this->_cursize = 0;
	   }

	   int StackSize()		//测量栈的大小
	   {
		   return this->_cursize;
	   }
	   bool StackEmpty()	//判断栈是否为空
	   {
		   return this->StackSize() == 0;
	   }
	   SNode *BuyNode()
	   {
		   SNode *p = new SNode;
		   if (NULL == p)
		   {
			   return NULL;
		   }
		   memset(p, 0, sizeof(SNode));
		   return p;
	   }
	   bool StackPush(ElemType kx)	//元素入栈
	   {
		   SNode *p=this->BuyNode();
		   if (NULL == p)
		   {
			   return false;		//申请节点失败,入栈失败
		   }
		   p->data = kx;
		   if (this->StackEmpty())		//栈为空的时候发生入栈同时影响栈顶和栈底指针
		   {
			   this->_buttom = this->_top = p;
		   }
		   else          //否则只会影响栈顶指针
		   {
			   this->_top->next=p;		//入栈
			   this->_top = p;		//栈顶指针重新指向新入栈的节点
		   }
		   this->_cursize += 1;
		   return true;
	   }
	   bool StackPop(ElemType &kx)		//元素出栈
	   {
		   assert(this->_buttom != NULL && this->_top != NULL);
		   if (this->StackEmpty())
		   {
			   return false;		//栈已空,无数据元素出栈
			}
		   SNode *p=this->_buttom;		//让p指向栈底
		   kx = this->_top->data;
		   if (this->StackSize() == 1)			//只有一个数据元素出栈的话同时影响栈顶指针和栈底指针
		   {
			   this->_buttom = this->_top = NULL;
		   }
		   else     //否则只影响栈顶指针
		   {
			   for (int i = 0; i < this->_cursize - 2; ++i)//让p指向栈顶指针前一个
			   {
				   p = p->next;
			   }
			   delete this->_top; 
			   this->_top = p;
		   }
		   this->_cursize -= 1;
	   }
	   void Print()
	   {
		   SNode *p = this->_buttom;
		   if (p == NULL)
		   {
			   return;
		   }
		   while (p != NULL)
		   {
			   cout << p->data << "  ";
			   p = p->next;
		   }
		   cout << endl;
	   }
private:
	SNode * _top;
	int _cursize;
	SNode *_buttom;
};

CLinkStack::CLinkStack()
{
	this->_top = this->_buttom = NULL;
	this->_cursize = 0;
}
CLinkStack::~CLinkStack()
{
	this->StackClear();
}

int main()
{
	ElemType arr[] = { 12,23,34,45,67};
	int n = sizeof(arr) / sizeof(ElemType);
	CLinkStack ls;
	for (int i = 0; i < n; ++i)
	{
		ls.StackPush(arr[i]);		//测试入栈函数
	}
	ls.Print();		//测试打印函数
	ElemType kx;
	while (!ls.StackEmpty())
	{
		ls.StackPop(kx);	//测试出栈函数
		cout << kx << "  ";
	};
	cout << endl;
	return 0;
}
运行结果

本程序在VS2017下运行通过。 

猜你喜欢

转载自blog.csdn.net/qq_41822235/article/details/81288253