2011年12月31日 星期六

C stake (struct)

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAXSIZE 10

typedef struct
{
  int item[MAXSIZE];
  int top;       
}Stack;

bool is_full(Stack s)
{
  return (s.top ==(MAXSIZE -1));             
}
bool is_empty(Stack s)
{
  return (s.top == -1);              
}


Stack create(Stack s)
{
   s.top =-1;
   return s;
                    
}
Stack push(Stack s ,int key)
{
  if(is_full(s))
    printf("Stack is Full\n");
  else{
       s.top=s.top+1;
       s.item[s.top] = key;
     }
     return s;    
}
Stack pop(Stack s)
{   
  if(is_empty(s))
    printf("Stack is empty");
  else
    {
     s.item[s.top]=0;            
     s.top= s.top-1;
    }  
    return s;   
      
}
void display(Stack s)
{
  int i; 
  for(i=0;i<=s.top;i++)
   printf("item[%d]=%d\n",i,s.item[i]);
}


int main()
{
   Stack s;
   s= create(s); 
   int  key;
   int choice;
   printf("--------------------------------\n");
   printf("1.push:\n"); 
   printf("2.pop:\n");
   printf("3.display stack\n");
   printf("--------------------------------\n");
  
   do{
       printf("Enter the function number>");
       scanf("%d",&choice);
       if(choice == 1){
           printf("please input a number to push :\n");
           scanf("%d",&key);     
           s=push(s,key);
       }
       else if(choice == 2)
           s=pop(s);
       else if(choice == 3)
          display(s); 
                
    }while(choice != -1);
   
    system("pause");   
}

沒有留言:

張貼留言