2017-10-16 45 views
2

我正在尝试创建一个队列链接,并且正在传递链接引用的引用,并且它没有工作并给出错误。使用引用无法正常工作的遍历链接列表

在函数'void insertDataToQueue(Node **,int)'中: 请求'* temp'中的成员'next',它的指针类型为'Node * {aka node *}'(也许你打算使用' - >'?

void insertDataToQueue(Node **queueList, int burstTime){ 
    Node *newNode = new Node; 
    newNode->burstTime = burstTime; 
    newNode->next = NULL; 

if(queueList == NULL){ 
    *queueList = newNode; 
} 
else{ 
    Node **temp = queueList; 
    while(*temp != NULL) 
     temp = *temp->next; 
} 
} 
+1

成员访问比解除引用具有更高的优先权,请参阅[这里](http://en.cppreference.com/w/cpp/language/operator_precedence) – user463035818

+0

那么我该如何遍历这个列表? –

+0

为了什么目的你正在写一个数据结构(它已经存在于'namespace std'中)? – Caleth

回答

0

*temp->next; 

被解析为

*(temp->next); 

因为-> has higher precedence than *,如果你想先提领,然后访问该成员可以使用括号:

(*temp)->next; 
+1

但是'temp'是'Node **'。我认为他必须这样声明:'Node * temp = * queueList' – Garf365

+1

@ Garf365 tbh一旦有多个'*',我就会丢失。由于我意识到可以在没有指针的情况下编写C++,所以不再习惯这种东西。我试图将答案专注于所要求的行,它可能不是唯一的错误 – user463035818

+1

我刚才提到,因为在你的答案中,这行'temp =(* temp) - > next;'产生一个错误,因为temp是'Node **'和'(* temp) - > next;'是'Node *' – Garf365

2

遍历整个列表,只是一个简单的指针Node是不够的:

void insertDataToQueue(Node **queueList, int burstTime){ 
    Node *newNode = new Node; 
    newNode->burstTime = burstTime; 
    newNode->next = NULL; 

    if(queueList == NULL) { 
     *queueList = newNode; 
    } 
    else { 
     Node *temp = *queueList; 
     // Find last element, ie element who "next" field is NULL 
     while(temp->next != NULL) { 
      temp = temp->next; 
     } 
     // Make last element to point to new element 
     temp->next = newNode; 
    } 
} 

现在,没有任何联系,我想(我希望)仅用于学习方面。因为C++作为你需要的每个容器。例如,你有std::liststd::queue谁是链接列表。对于生产代码,更喜欢使用它,而不是自己开发。