我有一个CircularLinkedList的代码,但这里的"printList"函数表现得很奇怪



下面是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图片:代码输出有人能解释为什么会发生这种事吗?

对于C++中的初学者,应该使用运算符new,而不是标准的C函数malloc。

然而,在这个代码片段之后

Node *newNode = (Node*)(malloc(sizeof(Node)));
newNode->data = num;
newNode->next = NULL;
if(head == NULL){
head = newNode;
tail = newNode;
return;
}

指针头->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;
}

最新更新