#2
azzbcc2016-05-15 10:40
|
程序代码:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 3
#define INCREASESIZE 3
typedef struct SqListQueeu
{
int *elem;
int front;
int rear;
int maxsize;
int increasesize;
}SqQueue;
bool Init(SqQueue &Q)//初始化队列
{
Q.elem = (int *)malloc(MAXSIZE * sizeof(int));//18
Q.maxsize = MAXSIZE;
Q.increasesize = INCREASESIZE;
Q.front = Q.rear = 0;
}
void increase(SqQueue &Q)//进队列
{
Q.elem = (int *)realloc(Q.elem, (Q.maxsize + Q.increasesize) * sizeof(int));
Q.maxsize += Q.increasesize;
}
void EnQueue(SqQueue &Q, int e)//入队列
{
if (Q.front == (Q.rear + 1) % Q.maxsize)
increase(Q);
Q.elem[Q.rear] = e;
Q.rear = (Q.rear + 1) % Q.maxsize;
}
bool is_empty(SqQueue Q)//判空
{
if (Q.front == Q.rear)
return true;
else
return false;
}
int length(SqQueue Q)//求队列的长度
{
return (Q.rear - Q.front + Q.maxsize) % Q.maxsize;
}
bool DeQueue(SqQueue &Q, int &e)//出队列
{
if (is_empty(Q))
{
printf("Queue is empty! ^_^ \n");
e = 0;
return false;
}
e = Q.elem[Q.front];
Q.front = (Q.front + 1) % Q.maxsize;
return true;
}
bool print(SqQueue Q)//输出元素
{
int e;
while (!is_empty(Q))
{
DeQueue(Q, e);
printf("%d ", e);
}
printf("\b\b \n");
}
int main()
{
SqQueue Q;
Init(Q);
EnQueue(Q, 0);
EnQueue(Q, 1);
EnQueue(Q, 2);
EnQueue(Q, 3);
EnQueue(Q, 4);
EnQueue(Q, 5);
EnQueue(Q, 6);
EnQueue(Q, 7);
EnQueue(Q, 8);
EnQueue(Q, 9);
printf("LENGTH = %d\n", length(Q));
print(Q);
return 0;
}
#include <stdlib.h>
#define MAXSIZE 3
#define INCREASESIZE 3
typedef struct SqListQueeu
{
int *elem;
int front;
int rear;
int maxsize;
int increasesize;
}SqQueue;
bool Init(SqQueue &Q)//初始化队列
{
Q.elem = (int *)malloc(MAXSIZE * sizeof(int));//18
Q.maxsize = MAXSIZE;
Q.increasesize = INCREASESIZE;
Q.front = Q.rear = 0;
}
void increase(SqQueue &Q)//进队列
{
Q.elem = (int *)realloc(Q.elem, (Q.maxsize + Q.increasesize) * sizeof(int));
Q.maxsize += Q.increasesize;
}
void EnQueue(SqQueue &Q, int e)//入队列
{
if (Q.front == (Q.rear + 1) % Q.maxsize)
increase(Q);
Q.elem[Q.rear] = e;
Q.rear = (Q.rear + 1) % Q.maxsize;
}
bool is_empty(SqQueue Q)//判空
{
if (Q.front == Q.rear)
return true;
else
return false;
}
int length(SqQueue Q)//求队列的长度
{
return (Q.rear - Q.front + Q.maxsize) % Q.maxsize;
}
bool DeQueue(SqQueue &Q, int &e)//出队列
{
if (is_empty(Q))
{
printf("Queue is empty! ^_^ \n");
e = 0;
return false;
}
e = Q.elem[Q.front];
Q.front = (Q.front + 1) % Q.maxsize;
return true;
}
bool print(SqQueue Q)//输出元素
{
int e;
while (!is_empty(Q))
{
DeQueue(Q, e);
printf("%d ", e);
}
printf("\b\b \n");
}
int main()
{
SqQueue Q;
Init(Q);
EnQueue(Q, 0);
EnQueue(Q, 1);
EnQueue(Q, 2);
EnQueue(Q, 3);
EnQueue(Q, 4);
EnQueue(Q, 5);
EnQueue(Q, 6);
EnQueue(Q, 7);
EnQueue(Q, 8);
EnQueue(Q, 9);
printf("LENGTH = %d\n", length(Q));
print(Q);
return 0;
}
在书中18行是 Q.elem = (int *)malloc((MAXSIZE + 1) * sizeof(int));
请问为什么要这样分配空间,这样不是浪费内存吗?
若不分配会出现什么问题?
[此贴子已经被作者于2016-5-14 19:23编辑过]