栈初始化算法
A. 求用C语言编写一个程序实现顺序栈初始化,出栈,入栈,判栈空,判栈满,急需,谢谢
#define STACK_SIZE 100
#define PUSH_POP_SUCCESS 1
#define PUSH_POP_ERROR 0
struct _stackbuf {
int _collection[STACK_SIZE];
int _top;
};
typedef struct _stackbuf S_STACK;
typedef unsigned int u_int_f;
// 入栈
u_int_f push(S_STACK *stack, int d){
if (stack->_top >= STACK_SIZE) return PUSH_POP_ERROR;
stack->_collection[stack->_top++] = d;
return PUSH_POP_SUCCESS;
}
// 出栈
u_int_f pop(S_STACK *stack, int *e){
if (!stack->_top) return PUSH_POP_ERROR;
*e=stack->_collection[--(stack->_top)];
return PUSH_POP_SUCCESS;
}
int main(){
S_STACK stack = { {0},0 };
push(&stack, 1);
push(&stack, 2);
push(&stack, 3);
int gv = 0;
pop(&stack, &gv);
printf("%d\n", gv);
system("PAUSE");
return 0;
}
B. C语言编程实现顺序栈的初始化,入栈,出栈,取栈顶元素,显示操作
#define STACKSIZE 100
int mstack[STACKSIZE],top,bottom;
void mInitStack() { top=bottom=0; }
void mPush(int x) { if ( top-bottom<=STACKSIZE ) { mstack[top]=x; top++; } }
int mPop() { int r=0; if ( top>bottom ) { r=mstack[top]; top--; } return r; }
void mShowStack() { int i; printf("["); for ( i=bottom;i<top;i++ ) printf("%d ",mstack[i]); printf("]
"); }
void main()
{
int i,n,x,loop=1,s;
char buffer[80];
mInitStack();
scanf("%d",&n); for ( i=0;i<n;i++ ) { scanf("%d",&x); mPush(x); }
mShowStack();
while ( loop )
{ buffer[1]=0; gets(buffer); s=1;
switch ( buffer[1] )
{ case 'O':
case 'o': x=mPop(); break;
case 'U':
case 'u': x=atoi(buffer+5); mPush(x); break;
case 'n':
case 'N': loop=0; break;
default: s=0; break;
}
mShowStack();
}
mShowStack();
}