2011年12月31日 星期六

C stack (struct linklist)

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


typedef struct Stack {
 int data;
 struct Stack *link;    
}Stack;

struct Stack *top =NULL;
struct Stack *tmp =NULL;
struct Stack *current =NULL;

struct Stack push(Stack s,int key)
{
  tmp = (struct Stack *)malloc(sizeof(struct Stack));
  tmp->data= key;
  tmp->link =top;
  top=tmp;
  return s;
      
}

struct Stack pop(Stack s)
{
  if(top==NULL)
    printf("no data\n");
  else
  {    
      tmp =top;
      top =top->link;
      free(tmp);
      return s;
  }   
}

struct Stack display(Stack s)
{
  current = (struct Stack *)malloc(sizeof(struct Stack));
  current =top;
  if(current==NULL)
    printf("no data\n");
  else
    {
      while(current != NULL)
      {
         printf("%d \n",current->data);
         current=current->link;       
      }             
    }    
}


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){
           printf("choice == 2\n");
           s=pop(s);
           }
       else if(choice == 3)
          display(s); 
                
    }while(choice != -1);
   
    system("pause");   
}

沒有留言:

張貼留言