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("]\n"); }
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();
}
#include<stdio.h>
#include<stdlib.h>
#define SIZE 100
typedef struct __Stack
{
int *data;
int pos;
}Stack;
int Stack_Initial(Stack *stack)
{
stack->data = (int*) malloc(sizeof(int));
if(stack->data == NULL) return 0;
stack->pos = -1;
}
int Stack_Push(Stack *stack,int value)
{
if(stack->pos == (SIZE-1) )
{
printf("栈已满\n");
return 0;
}
stack->pos++;
stack->data[stack->pos] = value;
return 1;
}
int Stack_Pop(Stack *stack)
{
if(stack->pos == -1) return 0;
stack->pos--;
return 1;
}
int Stack_GetTop(Stack *stack)
{
if(stack->pos == -1)
{
printf("栈为空\n");
return 0;
}
return stack->data[stack->pos];
}
void Stack_Show(Stack *stack)
{
if(stack->pos == -1)
{
printf("栈为空\n");
return;
}
for(int i = 0; i <= stack->pos;i++)
{
printf("%10d",stack->data[i]);
}
}
void Stack_Destroy(Stack *stack)
{
free(stack->data);
}