下面是CircularLinkedList的代码。我注意到,每当我在代码中调用printList函数时,函数调用都不会执行。为什么会这样呢?
typedef struct Node
{
int data;
struct Node *next;//this is called self-referential structure
} Node;
Node *head = NULL;//global head pointer
Node *tail = NULL;
void insertAtBeginning(int num){
Node *newNode = (Node*)(malloc(sizeof(Node)));
newNode->data = num;
newNode->next = NULL;
if(head == NULL){
head = newNode;
tail = newNode;
return;
}
newNode->next = head;
head = newNode;
tail->next = head;
}
void printList(Node *head){
if(head == NULL){
cout<<"List is empty"<<endl;
return;
}
Node* temp;
temp = head;
do{
cout<<temp->data<<" ";
temp = temp->next;
}while(temp != head);
}
int main(){
insertAtBeginning(1);
printList(head);
insertAtBeginning(2);
printList(head);
return 0;
}以上代码的输出结果如下:1图像:码输出,任何人都能解释为什么会发生这种情况吗?
发布于 2022-02-08 13:26:31
对于C++中的初学者,您应该使用新操作符,而不是标准的C函数malloc。
然而,在这个代码片段之后
Node *newNode = (Node*)(malloc(sizeof(Node)));
newNode->data = num;
newNode->next = NULL;
if(head == NULL){
head = newNode;
tail = newNode;
return;
}指针head->next和tail->next等于NULL。
因此,这段代码片段
Node* temp;
temp = head;
do{
cout<<temp->data<<" ";
temp = temp->next;
}while(temp != head);调用未定义的行为。
似乎您需要在if语句的正文中再添加一条语句。
if(head == NULL){
head = newNode;
tail = newNode;
tail->next = head;
return;
}https://stackoverflow.com/questions/71034600
复制相似问题