首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我有一个CircularLinkedList代码,但是这里的‘printList’函数的行为很奇怪

我有一个CircularLinkedList代码,但是这里的‘printList’函数的行为很奇怪
EN

Stack Overflow用户
提问于 2022-02-08 13:18:02
回答 1查看 28关注 0票数 -4

下面是CircularLinkedList的代码。我注意到,每当我在代码中调用printList函数时,函数调用都不会执行。为什么会这样呢?

代码语言:javascript
复制
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图像:码输出,任何人都能解释为什么会发生这种情况吗?

EN

回答 1

Stack Overflow用户

发布于 2022-02-08 13:26:31

对于C++中的初学者,您应该使用新操作符,而不是标准的C函数malloc。

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

代码语言:javascript
复制
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。

因此,这段代码片段

代码语言:javascript
复制
Node* temp;
temp = head;
do{
    cout<<temp->data<<" ";
    temp = temp->next;
}while(temp != head);

调用未定义的行为。

似乎您需要在if语句的正文中再添加一条语句。

代码语言:javascript
复制
if(head == NULL){
    head = newNode;
    tail = newNode;
    tail->next = head;
    return;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71034600

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档