2013年1月21日 星期一

[C Language][Stack] Using Array to make Basic Stack working function


[C Language][Stack] Basic Stack working function



#include <stdlib.h>

#include <stdio.h>

#define MaxSize 10

int stack[MaxSize];

int top=-1;

 

void push(int value)

{

   int i;

 

   if (top >= MaxSize)

      printf("The stack is full!!\n");

   else

   {

        top++;

        stack[top]=value;

 

        printf("[Push] The stack content (top->bottom):");

        for (i=top;i>=0;i--)

            printf("[%d]",stack[i]);

        printf("\n");

   }

}



 

int pop( )

{

     int temp;    

     int i;

 

     if (top <  0)    

     {

            printf("\nThe stack is empty!!\n");

            return -1;

     }

 

     temp=stack[top];    

     top--;        

     printf("The pop value is [%d] \n",temp);

     printf("[POP] The stack content (top->bottom):");

    for (i=top;i>=0;i--)

             printf("[%d]",stack[i]);

     printf("\n");

     return temp;

}

 

 

void main ( )

{

    int select;    

    int stack[5];

    int i,value;

 

 

    do

    {

        printf("\n[1]Input a stack data");

        printf("\n[2]Output a stack data");

        printf("\n[3]Exit");

        printf("\nPlease select one=>");

        scanf("%d",&select);

 

        switch (select)

        {

         case 1: printf("\nPlease input the data=>");

             scanf("%d",&value);

             push(value);

             break;

         case 2: value=pop( );

             break;

        }

 

    } while (select !=3);

}

0 意見:

張貼留言