#include <stdlib.h>
#define MAXSIZE 100
typedef struct _Queue
{
int front
int rear
int data[MAXSIZE]
}Queue
void addqueue(Queue *v,int num)
{
if(v->front==(v->rear+1)% MAXSIZE)
{
printf("The Queue is full!\n")
exit(1)
}
else
{
v->data[v->rear]=num/*就是你所写的那两句,稍作修改,再 交换位置即可*/
v->rear=(v->rear+1)% MAXSIZE
}
}
creat(Queue * v,int x)
{
if(((v->rear)+1)%MAXSIZE==v->front)
{
printf("The Queue is full!\n")
return 0
}
else
{
v->data[v->rear]=x
v->rear=((v->rear)+1)%MAXSIZE
return 1
}
}
void PrintEle(Queue *v)
{
int i=v->front
while(i%MAXSIZE!=v->rear)
{
printf("%3d",v->data[i])
i++
}
printf("\n")
}
void InitQueue(Queue *v)
{
v->front=0
v->rear=0
}
void main()
{
int n=0,x=0
Queue p
InitQueue(&p)
printf("Input elements for the Queue(input 0 exit):\n")
scanf("%d",&n)
while(n!=0)
{
creat(&p,n)
scanf("%d",&n)
}
printf("The Queue is:\n")
PrintEle(&p)
//add number
printf("put the insert num:")
scanf("%d",&x)
addqueue(&p,x)
//input the queue
printf("The inserted queue is:\n")
PrintEle(&p)
printf("\n")
}
输入数据形成队列都没问题,而插入数据却出现了问题。所以直接去查看void addqueue即可;观察后发现else体中:
1. 应该是v->data[v->rear]=num而不是你所写的v->data[v->rear]=x,因为你的x没赋初值,且是你自己定义的,不是插进来的数。
2.只需将你所写的addqueue函数,增加一个形参num,再交换你所写的那两句即可!
#include <stdio.h>#include <stdlib.h>
#define MAXQSIZE 100 //最大队列长度
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef struct
{
int *base
int front
int rear //尾指针,若队列不空,指向队列尾元素的下一个位置
}SqQueue
void InitQueue(SqQueue *Q)
{
Q->front = Q->rear = 0
if (Q->base == NULL) {
Q->base = (int*)malloc(sizeof(int)* MAXQSIZE)
}
}
void DesQueue(SqQueue *Q) {
free(Q->base)
Q->base = NULL
Q->front = Q->rear = 0
}
int QueueLength(SqQueue *Q)
{
if (Q->base == NULL) return ERROR
return (Q->rear - Q->front + MAXQSIZE) % MAXQSIZE
}
void display(SqQueue *Q)
{
int i
if (Q->base == NULL) {
printf("\n ERROR ")
return
}
for (i = Q->front i != Q->rear i++) {
i = i % MAXQSIZE
printf("%3d", Q->base[i])
}
printf("\n")
}
int InQueue(SqQueue *Q, int e)
{
if (Q->base == NULL) return ERROR
if ((Q->rear + 1) % MAXQSIZE == Q->front)
return OVERFLOW
Q->base[Q->rear] = e
Q->rear = (Q->rear + 1) % MAXQSIZE
return OK
}
int DeQueue(SqQueue *Q, int m)
{
int i = 0
if (Q->base == NULL) return ERROR
if (Q->front == Q->rear)
return ERROR
while (i != m && Q->front != Q->rear)
{
printf("\n%dDeleted\n", Q->base[Q->front])
Q->front = (Q->front + 1) % MAXQSIZE
i++
}
if (i != m) {
printf("\n ERROR ")
return ERROR
}
return OK
}
void main()
{
int m, n, d, i
SqQueue Q = { 0, 0, 0 }
InitQueue(&Q)
printf("请输入要插入的元素个数:")
scanf("%d", &m)
printf("要插入的元素:")
for (i = 1 i <= m i++)
{
scanf("%d", &n)
InQueue(&Q, n)
}
printf("插入元素后,队列中的元素为:")
display(&Q)
printf("队列长度为:")
printf("%d\n", QueueLength(&Q))
printf("输入要删除的元素个数:")
scanf("%d", &d)
DeQueue(&Q, d)
printf("\n删除元素后,队列中元素为:")
display(&Q)
printf("\n")
DesQueue(&Q)
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)