順序表堆棧的操作實現源碼

//堆棧的實現,順序表的實現
//編寫一個C源程序,其中包含順序表示的空棧的創建、判斷棧是否爲空、進棧、出棧、取棧頂元素等操作
int main(){
SLNode *phead;
phead=InitiateHead(phead);
cout<<"首地址2.1:"<<phead<<endl;//此爲頭指針的地址 
menu();
operation(phead);

return 0;

}
//操作實現代碼:

//初始化 
int initiate(Stack **s){
       *s=(Stack *)malloc(sizeof(Stack));
      (*s)->top= 0;
    // cout<< s->top;
     return 1;
}
//判斷棧是否爲空 
int Empty_stack(Stack *s){
     if(s->top<=0){
       cout <<"棧爲空!"<<endl;
       return 0;
     }else if(s->top>=MaxSize-1){
         cout<<"棧滿了,無法進行壓棧操作!"<<endl;
         return 3;
       
     }else{
      cout<<"棧不爲空!"<<endl; 
      return 1;
     } 
} 
//創建棧
int Create_Stack(Stack *s){
       int i=0; 
  cout<<"請創建棧:"<<endl;
  cout<<"______________________________top:"<<endl;
  cout<<"期待有人能教我解決這個輸入的問題,希望簡單明瞭!"<<endl; 
  for(int i = 0;i < 10;i++){
      if(s->top>=MaxSize){
       break;
     }
    s->stack[s->top]=i+1;
    s->top++;    
      }
       cout<<"________________________________top:"<<endl; 
       /*cout<<"________________________________top:"<<endl;
  for(int i = 0;;i++){
    cin>>i;
      if(s->top<MaxSize&&getchar()=='\n'){
       break;
   }
    s->stack[s->top]=i+1;
    s->top++;    
      }
       cout<<"________________________________top:"<<s->top<<endl; *///這裏有個問題希望有人能夠指點,不知如何操作。。。求解,謝謝 
      return 1;
} 
//輸出棧內元素
 int out_Stack(Stack *s){
  for(int i = 0;i<s->top;i++){
       cout<<s->stack[i]<<endl;
} 
 } 
//壓棧 
int Push_Stack(Stack *s,DataType x){
     if(Empty_stack(s)==3){
      return 1;
     }else{
        s->stack[s->top] = x;
        s->top++;
        cout<<x<<endl; 
   return 1;
     }
}
//出棧
int Stack_Pop(Stack *s){
Empty_stack(s);
cout<<"________________________________top:"<<s->top<<endl;
    while(s->top!=NULL){
  s->top--;
  cout<<s->stack[s->top]<<endl;
    }
    cout<<"________________________________top:"<<s->top<<endl;
    return 1;   
} 
//取棧頂元素
int  Stack_Top(Stack *s,DataType *d){
if(s->top<= 0){
     Empty_stack(s);
}else{
*d=s->stack[s->top-1];
}
return 1;
} 
//主函數

int main(){
  Stack *p;
  int x;
  initiate(&p);
  Empty_stack(p);
  Create_Stack(p);
  cout<<"創建好後的棧中的元素:"<<endl; 
  out_Stack(p);
  cout<<"壓棧:"<<endl;
  Push_Stack(p,100);
  cout<<"出棧:"<<endl;
       Stack_Pop(p);
       cout<<"取棧頂元素:"<<endl;
       Stack_Top(p,&x);
       cout<<x<<endl;
  return 0;
}

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章