带有头结点,头指针真,尾指针的栈基本操作

#include<iostream>
using namespace std;

typedef char elemtype;

/*带有头结点,头指针真,尾指针的栈基本操作*/
struct Stack
{
    elemtype data;
struct Stack *next;
};//*PStack;
//PStack ptop;
//PStack pbottom; //定义头指针,尾指针
Stack *ptop,*pbottom;

/*生成头结点,尾指针和头指针都指向他*/
void initStack()
{
  pbottom=new Stack;
  pbottom->next=NULL;
  ptop=pbottom;
}

void display()
{
  Stack *point=ptop;
  while(point!=pbottom)
  {
   cout<<point->data<<" "<<endl;
   point=point->next;
  }
  cout<<endl;
}

/*判断栈是否为空的函数*/
bool isEmpty()
{
    if(pbottom==ptop)
  return true;
    else
     return false;

}

/*得到栈顶元素*/
void GetTop()
{
  if(isEmpty()==true)
   cout<<"栈为空"<<endl;
  else
  cout<<"栈顶元素为: "<<ptop->data<<endl;
 
}

/*进栈*/
void pushStack()
{
  Stack *point=new Stack;
  cout<<"请输入值"<<endl;
  cin>>point->data;
  point->next=ptop;
  ptop=point;
}
 
/*出栈*/
void popStack()

  if(isEmpty()==true)
   cout<<"栈为空"<<endl;
   else
   {cout<<"出栈的元素为: "<<ptop->data;
   

    ptop=ptop->next;
 
 
    }
}

int main()

   initStack();
   GetTop();
   pushStack();
   pushStack();
   pushStack();
   display();
   popStack();
   display();
   display();
   pushStack();
   GetTop();
   display();
return 0;
}

 

关于栈的销毁,delelte只能回收new的节点,还没搞出来。参考http://www.cnblogs.com/uniqueliu/category/307731.html

你可能感兴趣的:(带有头结点,头指针真,尾指针的栈基本操作)