调试了很久,结果感觉没什么问题,但是在学校系统上提交就是WA,崩溃了,先放上代码,之后再改
#include<iostream>
using namespace std;
struct Queue {
int head;
int rear;
int length;
int *data;
};
void initQueue(Queue* Q, int n) {
Q->head = 0;
Q->rear = -1;//rear初始化为-1
Q->length = 0;
Q->data = (int*)malloc(sizeof(int) * n);
}
bool isEmpty(Queue* Q) {
return Q->length <= 0;
}
void pop(Queue* ptr, int k) {
if (ptr->length <= 0) {
cerr << "队列为空" << endl;
return;
}
ptr->length--;
ptr->head = (ptr->head + 1) % k;
}
void append(Queue* Q, int e, int k) {
if (Q->length >= k) {
//cerr << "队列已满" << endl;
//return;
pop(Q,k);
}
Q->length++;
Q->rear = (Q->rear + 1) % k;
Q->data[Q->rear] = e;
}
void showQueue(Queue Q, int k) {
if (Q.length <= 0) {
cerr << "队列为空" << endl;
return;
}
int begin = (Q.rear + 1) % k;
while (begin != Q.rear) {
cout << Q.data[begin] << " ";
begin = (begin + 1) % k;
}
cout << Q.data[Q.rear] << endl;
}
int returnCount(Queue Q) {
return Q.length;
}
void feibonaqi(Queue *q,int k,int MAX) {
/*q.base[k + 1].val = 1; q.base[k + 2].val = 1;
for (int i = 3; ; i++) {
int temp = q.base[k + i - 1].val + q.base[k + i - 2].val;
if (temp < MAX)q.base[k + i].val = temp;
else break;
}*/
for (int i = 0; i < k-1; i++) {
append(q, 0, k);
}
int temp = 0;
append(q, 1, k);
while (q->data[q->rear] <= MAX) {
int new_val = q->data[q->rear] + temp;
temp = q->data[q->rear];//先把当前的数保存起来
if (new_val <= MAX)append(q, new_val,k);//入队新的元素
else break;
}
}
int main() {
int k, MAX;
Queue q;
cin >> MAX >> k;
if (k <= 1 || k >= 100)return 0;
if (MAX <= 0 || MAX >= 10000)return 0;
initQueue(&q,k);
//函数使队列内内容为最后k项的值
feibonaqi(&q,k, MAX);
//输出
showQueue(q,k);
}