栈的链式存储结构和操作实现.txt

来自「栈的链式存储结构和操作实现、 栈的链式存储结构和操作实现」· 文本 代码 · 共 85 行

TXT
85
字号
#include <cstdlib>
#include <iostream>

using namespace std;

typedef int ElemType;

struct SNode{
       ElemType data;
       SNode* next;
       };
       
void InitStack(SNode*& HS)//初始化栈链为空 
{
         HS=NULL;
}

void Push(SNode*&HS,const ElemType &item)//向栈链中插入一个元素 
{
         SNode* newptr=new SNode;
         newptr->data=item;
         newptr->next=HS;
         HS=newptr;
}

ElemType Pop(SNode*& HS)//从栈链中删除一个元素并返回 
{
         if(HS==NULL){
           cerr<<"Linked stack is empty!"<<endl;
           exit(1);
         }
         SNode *p=HS;
         HS=HS->next;
         ElemType temp=p->data; 
         delete p;
         return temp;
}

ElemType Peek(SNode* HS)//读取栈顶元素 
{
         if(HS==NULL){
           cerr<<"Linked stack is empty!"<<endl;
           exit(1);
         }
         return HS->data;
}
bool EmptyStack(SNode* HS)//判断栈是否为空 
{
     return HS==NULL;
} 

void ClearStack(SNode*& HS) //清空栈 
{
     SNode *cp,*np;
     cp=HS;
     while(cp!=NULL)
     {
         np=cp->next;
         delete cp;
         cp=np;
     }
     HS=NULL;
}
      
int main(int argc, char *argv[])
{
    SNode* a;
    InitStack(a);
    int x;
    cin>>x;
    while(x!=-1) {
               Push(a,x);
               cin>>x;
    }
    cout<<Peek(a)<<endl;
   while(!EmptyStack(a))
      cout<<Pop(a)<<" ";
    cout<<endl;
    ClearStack(a);


 system("PAUSE");
    return EXIT_SUCCESS;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?