运算符 - >在C++中无法正常工作

use*_*516 5 c++ operator-keyword

我在c ++中练习单链表(练习如何找到循环列表的起始节点),但发现使用运算符 - >非常混乱.我正在使用Visual Studio 2010 C++ Express

这非常有效: head->append(2)->append(3)->append(4)->append(5)

但这不起作用(创建循环链表): head->append(2)->append(3)->append(4)->append(5)->append(head->next)

当我跳转到这个方法并进行调试时,似乎head->next没有正确地传递给方法.

但这有效:

  1. Node* tail=head->append(2)->append(3)->append(4)->append(5); tail->append(head->next);
  2. 或者,以后我改return c->nextreturn head在这两种方法,head->append(2)->append(3)->append(4)->append(5)->append(head->next) 也适用.

我在这里错过了什么?谢谢!

我的代码详情如下:

void main(){
    Node* head=new Node(1);
    Node* tail=head->append(2)->append(3)->append(4)->append(5)->append(head->next);
    cin.get();
}

class Node{
public:
    Node* next;
    int data;
    bool marked;

    Node(int d){
        data=d;
        marked=false;
        next=NULL;
    }

    Node* append(int d){
        Node* c=this;
        while(c->next!=NULL){
            c=c->next;
        }
        c->next=new Node(d);
        return c->next;
    }

    Node* append(Node* n){
        Node* c=this;
        while(c->next!=NULL){
            c=c->next;
        }
        c->next=n;
        return c->next;
    }
};
Run Code Online (Sandbox Code Playgroud)

Dre*_*ann 10

您遇到了未定义的行为.

问题是你期望head->next在特定时间进行评估(在调用最后一次之前append().但这不能保证.