文档库 最新最全的文档下载
当前位置:文档库 › 简易停车场(C语言代码)

简易停车场(C语言代码)

废话不多说,就是栈的应用
#include
#include
typedef int elemtype;
struct stackcar /*定义栈,命名car*/
{
elemtype *stack; /*定义栈内指针*/
int top; /*定义栈顶*/
elemtype maxsize; /*定义栈空间*/
};
struct qnode /*定义节点*/
{
elemtype data; /*定义数据域*/
struct qnode *next; /*定义链队列的链接指针域*/
};
struct queuecar /*定义链队列,命名car*/
{
struct qnode *front; /*定义队首指针*/
struct qnode *rear; /*定义队尾指针*/
};
void initstack(struct stackcar *sc,int m)
{
sc->top=-1;
sc->maxsize=m;
}
void push(struct stackcar *sc,elemtype x)
{
sc->top++;
sc->stack[sc->top]=x;
}
elemtype pop(struct stackcar *sc)
{
sc->top--;
return sc->stack[sc->top+1];
}
void printstack(struct stackcar *sc) /*对栈的遍历*/
{
int j;
printf("The stack is:");
for(j=0;j<=sc->top;j++)
printf("%5d",sc->stack[j]);
}
void initqueue(struct queuecar *qc)
{
qc->front=qc->rear=NULL;
}
void enqueue(struct queuecar *qc,elemtype x)
{
struct qnode *np;
np=malloc(sizeof(struct qnode));
np->data=x;
np->next=NULL;
if(qc->rear==NULL)
qc->front=qc->rear=np;
else
qc->rear=qc->rear->next=np;
}
elemtype outqueue(struct queuecar *qc)
{
struct qnode *z;
elemtype temp;
if(qc->front==NULL)
{
printf("the queue is null,can not delete!\n");
return;
}
temp=qc->front->data;
z=qc->front;
qc->front=z->next;
if(qc->front==NULL)
qc->rear=NULL;
free(z);
return temp;
}

main()
{
int number;
int n,c=0,d=0; /*c表示在停车场里的位置(停车场计数器),d表示在便道里的位置(便道计数器)*/
int flag=1,cho; /*flag表示状态(程序进行、退出),cho表示选择*/
struct stackcar STp,STt,*p,*t; /*调用两次栈,建立p(停车场的栈),t(临时栈)*/
struct queuecar Qq,*q; /*调用一次队列,建立q(等候排队)*/
printf("The parking maxsize is:");
scanf("%d",&n);

initstack(&STp,n); /*初始化p,t,q*/
initstack(&STt,n);
initqueue(&Qq);
p=&STp;
t=&STt;
q=&Qq;

while(flag==1)
{
printf("\n1:drive in the parking 2:drive out the parking 0:quit Please choose:"); /*1:开入停车场 2:开出停车场 3:在队里等着 0:退出停车场程序*/
scanf("%d",&cho);
while(cho==0) /*退出停车场程序*/
{
return;
}
while(cho==1) /*开入

停车场*/
{
if(p->top==p->maxsize-1)
{
printf("stack is overflow!Please wait at the street!\n");
printf("Please input the driving into the car's number:");
scanf("%d",&number);
enqueue(q,number);
d++; /*便道计数器+1*/
printf("The car %d is parking on No.%d location on the street.\n",number,d); /*输出所输车辆所在便道上的位置*/
}
else
{
printf("\nPlease input the driving into the car's number:");
scanf("%d",&number);
push(p,number);
c++; /*停车场计数器+1*/
printf("The car %d is parking on No.%d location in the park.\n",number,c); /*输出所输车辆所在停车场内的位置*/
}
printstack(p);
break;
}
while(cho==2) /*开出停车场*/
{
printf("Please drive out the number of car:");
scanf("%d",&number);
if(p->top==-1)
printf("the stackcar is NULL!\n");
else
while(number!=p->stack[p->top])
{
push(t,p->stack[p->top]);
pop(p);
}
pop(p);
while(t->top!=-1)
{
push(p,t->stack[t->top]);
pop(t);
}
if(d>0)
{
push(p,q->front->data);
outqueue(q);
d--; /*便道计数器-1*/
}
if(p->top==-1)
printf("The stack is NULL!\n");
else
printstack(p);
break;
}
}
}

相关文档
相关文档 最新文档