火车调度问题
#define MAXSIZE 100/* 栈、队列的最大容量,设为100 */
#include <stdio.h>
#include <malloc.h>
typedef char datatype;
typedef struct {
datatype stack[MAXSIZE]; /* 装载栈的向量 */
int top; /* 栈顶指针 */
} seqstack; /* 顺序栈类型定义*/
typedef struct
{ datatype queue[MAXSIZE];
/* MAXSIZE为队列的最大长度 */
int front;
int rear;
} sequeue; /* 顺序队列类型定义*/
void setstacknull(seqstack *s ) /* 置空栈 */
{ s->top=-1; }
datatype pop(seqstack *s ) /* 出栈 */
{ if (s->top<0 )
{ printf( "stack empty!\n" );
return('\0');
}
else
{ s->top--; /* 产生新栈顶指针 */
return(s->stack[s->top+1]); /* 返回原栈顶元素值 */
}
}
int empty(seqstack *s) /* 判断是否为空栈 */
{
if (s->top<0 ) return(1);
else return(0);
}
void push(seqstack *s,datatype x) /* 入栈 */
{ if ( s->top>=MAXSIZE-1 ) /* 上溢 */
printf( "stack overflow!\n" );
else
{ s->top=s->top+1; /* 1.栈顶指针加1 */
s->stack[s->top]=x; /* 2.新元素入栈 */
}
}
void setseqnull(sequeue *sq) /* 置空队列 */
{
sq->front=-1; sq->rear=-1;
}
void encyque(sequeue *sq,datatype x) /* 入队 */
{
if((sq->rear+1)%MAXSIZE==sq->front)
printf( "queue overflow!\n" );
else
{ sq->rear=(sq->rear+1)%MAXSIZE;
sq->queue[sq->rear]=x;
}
}
datatype delcyque(sequeue *sq) /* 出队 */
{
if(sq->front==sq->rear)
return(NULL);
else
{ sq->front=(sq->front+1)%MAXSIZE;
return(sq->queue[sq->front]);
}
}
void main( )
{
seqstack *st;
sequeue *trainsq;
char ch, trains[MAXSIZE],*p=trains;
st=(seqstack *)malloc(sizeof(seqstack));
trainsq=(sequeue *)malloc(sizeof(sequeue));
setstacknull(st);
setseqnull(trainsq);
printf("enter train serious:\n");
gets(trains);
putchar('\n');
while (ch=*p ) {
if (ch=='L')
{ push(st,ch);
ch=pop(st);
encyque(trainsq,ch);}
else
{ push(st,ch);}
p=p+1;}
while(!empty(st)) {
ch=pop(st);
ch=trains[MAXSIZE];
printf("rest train serious:\n");
gets(trains);
putchar('\n');
while (ch=*p ) {
if (ch=='H') push(st,ch);
else
{ /* ch=='Q'*/
push(st,ch);
ch=pop(st);
encyque(trainsq,ch);}
p=p+1;}
while (!empty(st)) {
ch=pop(st);
encyque(trainsq,ch);
} }
printf("new train serious:\n");
while (ch=delcyque(trainsq)) putchar(ch);
putchar('\n');
}
想达到 输入QHLHQLHLQQLHHQLQH 结果输出LLLLLQQQQQQHHHHHH 这样的效果。
可是不知道为什么这个程序的运行输出的结果 LLLLLQQHHQQHQHHQ.
求指点!