以下是头文件Stack.h
#ifndef stack
struct stack;
typedef struct stack *ptostack;
typedef int topofstack;
ptostack createstack(int which);/* the parameter "which" helps us decide which stack we are going to create*/
void push(ptostack s,int newn,int move);
void pop(ptostack s,int move);
int isfull(ptostack s1,ptostack s2);
int how_many(char a[]);
#endif
以下是程序:
#include<stdio.h>
#include"C:\Win-TC\projects\Stack.h"
#define N 9
int num[N+1];
struct stack
{
topofstack top;
int *array;
int capacity;
};
ptostack createstack(int which)
{
int tmp;
ptostack s;
s=malloc(sizeof(struct stack));
tmp=N-N*which;/*which==0 means we create this stack to store even numbers,1 means odd numbers.They will use the same array but start from different point*/
s->array=&num[tmp]; /* even stack will start from num[N],odd stack will start from num[0]*/
s->top=tmp;
s->capacity=0;
/*we use this variable to record the amount of the numbers that in the stack at the present time*/
return s;
}
void push(ptostack s,int newn,int move)
{
s->top=s->top+move;
s->array[s->top]=newn;
/* move may be 1 or -1*/
s->capacity=s->capacity+1;
}
int isfull(ptostack s1,ptostack s2)
/*use this function to prevent collision between two stack*/
{
if(s1->capacity+s2->capacity==N+1)
return 1;
else return 0;
}
void pop(ptostack s,int move)
{
s->top=s->top+move;
s->capacity=s->capacity-1;
}
int top(ptostack s)
{
return s->array[s->top];
}
main()
{
/*in this case we will input some integers and use functions defined above to seperate them into two stacks according to that the number is odd or even */
int i,j,temp,move;
char g[4];
ptostack odd,even;
odd=createstack(1);
even=createstack(0);
printf("Please input 10 integers:\n");
i=0;
while(i<N+1)
{
scanf("%d",&temp); /*Do you remember that num is a global array?*/
if(temp%2==0) {push(even,temp,-1);}
else {push(odd,temp,1);}
i=i+1;
}
printf("the top of the odd stack is %3d\n",top(odd));
printf("the top of the even stack is %3d\n",top(even));
printf("Now we are going to test the pop function.\n");
printf("which stack do you want to perform this operation?\n");
scanf("%s",g);
if(!strcmp(g,"odd"))
move=-1;
else
move=1;
pop((ptostack)g,move);
printf("the top of the %s stack is %d\n",g,top((ptostack)odd));
getch();
}