69,377
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
int n=0;
typedef int ElemType;
typedef struct linknode
{
ElemType data;
struct linknode *next;
}linknode;
typedef struct Queue
{
linknode *front;
linknode *rear;
}linkqueue;
int initial(linkqueue *Q)
{
linknode *p;
p = (linknode *)malloc(sizeof(linknode));
if(!p)
{
exit(1);
return ERROR;
}
p->next = NULL;
Q->front = Q->rear = p;
return OK;
}
int Empty(linkqueue *Q)
{
return(Q->front == Q->rear?OK:ERROR);
}
int push(linkqueue *Q)
{
linknode *p;
p = (linknode *)malloc(sizeof(linknode));
if (!p) {
exit(1);
return ERROR;
}
printf("请输入进队整数:");
scanf("%d",&p->data);
Q->rear->next = p;
Q->rear = p;
n++;
return OK;
}
int pop(linkqueue *Q)
{
linknode *p;
if(Q->front == Q->rear)
return ERROR;
else
{
p = Q->front->next;
if(Q->front->next == Q->rear)
{
Q->front->next = NULL;
Q->rear = Q->front;
}
else
{
Q->front->next = p->next;
}
free(p);
n--;
return OK;
}
}
int gettop(linkqueue *Q)
{
linknode *p;
if(Q->front==Q->rear)
return ERROR;
else
{
p = Q->front->next;
}
return p->data;
}
void print(linkqueue *Q)
{
int i=0;
linknode *p;
if(Empty(Q))
printf("队为空!");
else
{
printf("队内元素为:");
for(p=Q->front->next;i<n; i++,p=p->next)
{
printf("%d ",p->data);
}
printf("\n队内元素个数为%d个",n);
}
}
int main(void)
{
linkqueue q;
linkqueue *Q;
Q=&q;
int i,e;
printf("1.链队初始化\n2.链队判空\n3.进队\n4.出队\n5.队顶\n6.遍历队\n7.退出\n\n\n");
while(scanf("%d", &i)!=EOF)
{
switch(i)
{
case 1:
if(initial(Q))
printf("初始化成功!");
break;
case 2:
if(Empty(Q))
printf("队空!");
else
printf("队未空!");
break;
case 3:
if(push(Q))
printf("进队成功!");
break;
case 4:
if(pop(Q))
printf("出队成功!");
else
printf("队为空!");
break;
case 5:
if(!gettop(Q))
printf("队为空");
else
{
e=gettop(Q);
printf("队顶元素为%d",e);
}
break;
case 6: print(Q);break;
case 7: exit(0);
}
putchar(10);
}
}
问题不大,主要是pop函数内,一个if判断表达式写成赋值表达式了。
注意是pop函数内的这句:
if(Q->front->next == Q->rear)