C++ 实现顺序栈与链式栈操作…


#ifndef __NODE_H__
#define __NODE_H__

//节点类模版
template//模版本质是将处理的数据类型说明为参数
struct Node
{
 //数据成员
 ElemType data;   //数据域
 Node*next; //指针域
 //构造函数
 Node(){next=NULL;}  //无实参
 Node(ElemType item,Node*link=NULL)
 {//已知数据元素和指针建立节点
  data=item;next=link;
 }
};
#endif

 


#ifndef __STACK_H__
#define __STACK_H__

#include "node.h"//节点类模版

#define STACK_SIZE 10000

//栈类模版
template
class Stack
{
public:
 Stack(){}
 virtual ~Stack(){}
 virtual bool Push(const ElemType &e)=0;//纯虚函数
 virtual bool Pop( ElemType &e)=0;
 virtual bool GetTop( ElemType &e) const=0;
};

//顺序栈类模版
template
class SqStack:public Stack
{
private:
 //顺序栈成员
 ElemType elem[STACK_SIZE]; //存栈元素值
 int top;     //栈顶
public:
 SqStack(){top=-1;}   //构造函数
 ~SqStack(){}

 bool Push(const ElemType &e)//入栈
 {
  if(top==STACK_SIZE-1)return false;
  else
  {
   elem[++top]=e;  //栈顶指针加1后将e入栈
   return true;
  }
 }
 bool Pop( ElemType &e)
 {
  if(top==-1)return false;
  else
  {
   e=elem[top--];
   return true;
  }
 }
 bool GetTop( ElemType &e)const
 {
  if(top==-1)return false;
  else
  {
   e=elem[top];
   return true;
  }
 }
};

//链式栈类模版
template
class LinkStack:public Stack
{
private:
 Node*top;  //栈顶指针
public:
 LinkStack(){top=NULL;}
 ~LinkStack()
 {
  ElemType e;     //临时变量
  while(top != NULL)Pop(e); //出栈,直到栈空
 }
 bool Push(const ElemType &e) //如果在函数里不需要对元素进行修改,进行常以用
 {
  top=new Node(e,top);
  //以e为数据值,top指向下一节点的构造新节点
  return true;
 }
 bool Pop(ElemType &e)
 {
  if(top==NULL)return false;
  else
  {
   e=top->data;   //用e返回栈顶元素
   Node*p=top; //暂存栈顶
   top=top->next;   //top指向下一节点
   delete p;    //释放原来的栈顶
   return true;   //出栈成功
  }
 }
 bool GetTop(ElemType &e)const
 {
  if(top==NULL)return false;
  else
  {
   e=top->data;
   return true;
  }
 }
};
#endif

 

 

main.cpp

#include
using namespace std;
#include "stack.h"

int main()
{
 int select=0;  //工作变量
 Stack*pStack; //指向栈的指针
 int e;    //元素
 
 do
 {
  cout<<"请选择(1:测试顺序栈,2:测试链式栈)";
  cin>>select;
 } while (select !=1&&select !=2);
 if(select==1)pStack=new SqStack;
 else pStack=new LinkStack;
 
 while(select!=5)
 {
  cout<<"1.生成栈"<<endl;
  cout<<"2.入栈"<<endl;
  cout<<"3:出栈"<<endl;
  cout<<"4:取栈顶栈"<<endl;
  cout<<"5:退出"<<endl;
  cout<<"选择功能(1~5):"<<endl;
  cin>>select;
 
  switch(select)
  {
  case 1:
   cout<<"输入e(e=0时退出):";
   cin>>e;
   while(e!=0)
   {
    pStack->Push(e);
    cin>>e;
   }
   break;
  case 2:
   cout<<"输入元素值:";
   cin>>e;
   pStack->Push(e);
   break;
  case 3:
   pStack->Pop(e);
   cout<<"栈顶元素值为:"<<e<<endl;
   break;
  case 4:
   pStack->GetTop(e);
   cout<<"栈顶元素值为:"<<e<<endl;
   break;
 
   }
   }
 delete pStack;

 return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值