在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: %sn", temp->data);
Print(operations);
Node * temp2 = Pop(&operations);
printf("Node2 popped is: %sn", temp2->data);
Print(operations);
// Other code down here... //
return 1;
}
我的流行代码:
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
永远不会工作。
我刚刚在实现GetOperations()和Print()时使用了您的代码。代码运行良好。
//Structure to represent node
typedef struct node
{
char *data;
struct node * next;
} Node;
//Pop top value from Linked list
Node * Pop (Node ** head)
{
if (*head == NULL)
{
printf("Error popping! List is empty.n");
return NULL;
}
Node * temp = *head;
*head = (*head)->next;
return temp;
}
//Create node and save data
Node *createNode(int i)
{
char *n=malloc(sizeof(4*sizeof(char)));
n[0]='O'; n[1]='p'; n[2]=(char)(((int)'0')+i); n[3]=' ';
Node *temp=(Node*)malloc(sizeof(struct node));
temp->data=n;
temp->next=NULL;
return temp;
}
//Create a list with data
Node* GetOperations()
{
int i;
Node *head=NULL,*current;
for(i=0;i<5;i++)
{
if(head==NULL)
{
head=createNode(i+1);
current=head;
}
else
{
Node *temp=createNode(i+1);
current->next=temp;
current=temp;
}
}
return head;
}
//Print the linked list
void Print(Node *ptr)
{
while(ptr)
{
printf("%s",ptr->data);
ptr=ptr->next;
if(ptr) printf("->");
}
printf("n");
}
//Start of program execution
int main()
{
Node * operations = GetOperations(); // Retrieve linked-list of operations
Print(operations); // Print list
if (operations == NULL) return 0;
Node *temp=NULL;
temp = Pop(&operations);
printf("Node popped is: %sn", temp->data);
free(temp); // Free popped data's memory
Print(operations);
temp = Pop(&operations);
printf("Node2 popped is: %sn", temp->data);
free(temp); // Free popped data's memory
Print(operations);
// Other code down here... //
return 0;
}
我得到了这个输出:
Op1->Op2->Op3->Op4->Op5
Node popped is: Op1
Op2->Op3->Op4->Op5
Node popped is: Op2
Op3->Op4->Op5