用链式结构表示栈的各种操作

来源:互联网 发布:软件培训要多久 编辑:程序博客网 时间:2024/05/24 07:30

#include<iostream.h>
#include<stdlib.h>
#define error 0
#define ok 1

typedef int elemtype;
typedef struct StackNode{
elemtype data;
struct StackNode *next;
}StackNode,*LinkStack;
int StackInit(LinkStack &S) 

                  
   S= (StackNode*)malloc(sizeof(StackNode)); 
   if(!S)   return error;
   S= NULL; 
    return ok;  

 int StackPush(LinkStack &S,elemtype e) 

   LinkStack p; 
    p = (StackNode *)malloc(sizeof(StackNode));
 p->data=e;
    p->next = S;                               
    S= p;                                    
    return ok; 

int StackPop(LinkStack &S,elemtype &e) 

    LinkStack p; 
  
    if(S != NULL) 
    {   e = S->data; p = S;
      
  S= S->next;                  
        delete(p);                                
    }    
 else 
        cout<<"stack empty!/n"; 
     return ok;  
}                           
        
     
 
 int Putout(LinkStack S )
{   LinkStack p;
 p=S;
  if(S==NULL) return error;
cout<<"输出所有元素";
while(p)
{cout<<p->data<<" ";
p=p->next;}
return ok;
}

 


int main() 

    LinkStack  S; 
     StackInit(  S); 
   int e,i,n;
   cout<<"输入栈的长度n:";
   cin>>n;
    for(i=0;i<n;i++)
 {cout<<"请输入进栈的元素:";
    cin>>e;
  StackPush( S,e);  
    }
 Putout( S);
 
 cout<<"输入要插入到栈中的元素";
 cin>>e; StackPush( S,e); Putout( S);
  cout<<"\n删除栈顶元素出栈的结果为:"; 
  StackPop( S,e);
  Putout( S);
 
 cout<<endl;
    return 0;
  }  

   

原创粉丝点击