창고 의 기본 조작 - 데이터 구조
2121 단어 데이터 구조
기본 작업: 스 택 초기 화, 스 택 에 들 어가 고 스 택 에서 나 오 며 스 택 꼭대기 요 소 를 가 져 와 빈 스 택 인지 판단 하고 스 택 을 비 웁 니 다.
예 코드:
#include
#include
#include
#define Initsize 100
#define Increase 100
#define ERROR 0
#define OK 1
#define OVERFLOW -1
typedef int Status;
typedef int Elemtype;
typedef struct SqStack
{
Elemtype *base,*top;
int stacksize;
}SqStack;
//init stack
Status InitStack(SqStack &s)
{
s.base=(Elemtype*)malloc(Initsize*sizeof(Elemtype));
if(!s.base) return ERROR;
s.top=s.base;
s.stacksize=Initsize;
return OK;
}
//push stack
Status Pushstack(SqStack &s,Elemtype e)
{
Elemtype *temp;
if(s.top-s.base+1>=s.stacksize)//stack full
{
temp=(Elemtype*)realloc(temp,(Increase+s.stacksize)*sizeof(Elemtype));
if(!temp) return ERROR;
s.base=temp;
s.top=s.base+s.stacksize; //remalloc changes the s.top's address,relocate s.top pointer
s.stacksize+=Increase;
}
*s.top=e;
s.top++;
return OK;
}
//stack if empty
bool EmptyStack(SqStack s)
{
if(s.base==s.top) return true;
else return false;
}
//print stack
Status DisplayStack(SqStack s)
{
if(EmptyStack(s)) printf("Stack is empty!
");
else
{
while(s.top!=s.base)
{
s.top--;
printf("%d ",*s.top);
}
printf("
");
}
return OK;
}
//top elem pop stack
Status PopStackelem(SqStack &s)
{
if(EmptyStack(s))
{
printf("Stack is empty!
");
return ERROR;
}
s.top--;
return OK;
}
//get top elem
Elemtype GetStacktop(SqStack s,Elemtype &e)
{
if(EmptyStack(s))
{
printf("Stack is empty!
");
return ERROR;
}
s.top--;
e=*s.top;
return OK;
}
Status ClearStack(SqStack &s)
{
s.top=s.base;
s.stacksize=0;
return OK;
}
int main()
{
SqStack stack;
int n,i;
Elemtype e;
InitStack(stack);
printf("Input n and the num:");
scanf("%d",&n);
for(i=0;i