只是在 C 中为我的链表实现 Pop 函数时遇到了一些麻烦。
这是一个非常奇怪的错误,因为它在第一次运行时不起作用。
Node * operations = GetOperations(); // Retrieve linked-list of operations
Print(operations);
while (1) {
if (operations == NULL) {
return 0;
}
Node * temp = Pop(&operations);
printf("Node popped is: %s\n", temp->data);
Print(operations);
Node * temp2 = Pop(&operations);
printf("Node2 popped is: %s\n", temp2->data);
Print(operations);
// Other code down here... //
return 1;
}
还有我的 Pop 代码:
Node * Pop (Node ** head) {
if (*head == NULL) {
printf("Error popping! List is empty.\n");
return NULL;
}
Node * temp = *head;
*head = (*head)->next;
return temp;
}
我的节点的代码:
typedef struct node {
char * data;
struct node * next;
} Node;
当我运行程序并返回 GetOperations 时(其中->
代表下一个节点):
Op1->Op2->Op3...
我得到以下输出:
Operations: Op1->Op2->Op3
Node popped is: (null)
Operations: Op1->Op2->Op3
Node2 popped is: Op1
Operations: Op2->Op3
如您所见,第一个pop
永远不会起作用。