2017-10-16 48 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誰是鏈接列表。對於生產代碼,更喜歡使用它,而不是自己開發。