0
我的C代码有点问题。我想用一些函数实现一个简单的队列,但pop函数不起作用。开始的项目不会被取消。我只是不知道为什么。如果你能帮助我,那你真好。 下面的代码:C - 流行音乐无法正常工作
#include <stdio.h>
#include <stdlib.h>
struct item{
struct item* toNext;
int value;
};
void printQueue(struct item* start){
if(start == NULL){
printf("\n");
return;
}
else{
printf("%d\n", start->value);
printQueue(start->toNext);
}
}
int pop(struct item* start){
if(start == NULL){
return -1;
}
else{
int tmp = start->value;
start = NULL;
return tmp;
}
}
int main(int argc, char *argv[]){
struct item* beginning;
struct item* current;
struct item* next;
current = (struct item*) malloc(sizeof(struct item));
current->value = 1;
current->toNext = NULL;
beginning = current;
int i;
for(i = 2; i <= 4; i++){
next = (struct item*) malloc(sizeof(struct item));
next-> value = i;
next-> toNext = NULL;
current->toNext = next;
current = next; // TODO
}
printQueue(beginning);
int tmp = pop(beginning);
printf("%d\n",tmp);
printQueue(beginning);
return 0;
}
,输出是:
1
2
3
4
1
1
2
3
4
虽然它应该是:
1
2
3
4
1
2
3
4
有谁知道这里有什么问题? 感谢您的回答。
您的pop()函数接收指针的拷贝到队列的头。 (您也可以将其视为接收整个队列的只读“副本”)。但是弹出功能需要修改队列。所以你将不得不重新安排事情。 –
因此,对该副本的任何更改都不会反映在原始副本中(主副本中)。 –
为什么你明确地为'main'中的队列分配节点?所有的队列交互都应该通过队列接口,即函数和一个空队列由一个'NULL'头指针来表示。 (啊,我现在看到的:你有没有'push'功能。) –