2016-01-13 42 views
0

注:我已經得到了預期的功能,使用我自己的代碼,但我看到另一個網站上的教程,並且想知道爲什麼它不起作用。基本的C鏈表語法錯誤

https://www.eskimo.com/~scs/cclass/int/sx8.html

前提如下:

我有一個非常基本的鏈表打轉轉:

typedef struct node { 
    int val; 
    struct node * next; 
} node_t; 

我想有一個函數刪除由值的條目。這是因爲如下:

int remove_by_value(node_t ** head, int val) { 
    for(head = &node_t; *head != NULL; head = &(*head)->next){ 
     if ((*head)->val == val) { 
      *head = (*head)->next; 
      break; 
     } 
    } 
} 

然而,當調用這個函數,即我得到一個錯誤:

"prog.c:35:17: error: expected expression before 'node_t' 
for(head = &node_t; *head != NULL; head = &(*head)->next){ 
^" 

任何想法?這只是一個簡單的語法錯誤,我沒有看到?謝謝!

+4

這是什麼'head =&node_t'用於? –

+0

除了語法錯誤之外,拼接元素的邏輯是錯誤的。 –

+0

嘗試「爲(; ...)」,i..e離開過tghe「頭= node_t」) –

回答

2

問題的根源在於node_t是一個類型,而不是一個變量,並且不能取某個類型的地址。

以下代碼乾淨地編譯。

一定要檢查的邏輯,

  1. 爲循環的第一次迭代時head = NULL或僅一個在鏈表結構
  2. 檢查邏輯,用於當期望結構或者是最後一個或倒數第二鏈表

這裏是代碼:

typedef struct node 
{ 
    int val; 
    struct node * next; 
} node_t; 


int remove_by_value(node_t ** head, int val) 
{ 
    int retVal = -1; // initialize to failed 
    node_t *previousNode = *head; 
    node_t *currentNode = *head; 

    for(; 
     previousNode && currentNode; // assure something to test 
     previousNode = currentNode, // update the pointers 
     currentNode = currentNode->next) 
    { 
     if (currentNode->val == val) 
     { 
      previousNode->next = currentNode->next; 
      retVal = 0; // indicate success 
      break; 
     } 
    } 
    return retVal; 
} // end function: remove_by_value 
+0

謝謝很多爲清楚的解釋。沒有意識到我正在嘗試對typedef執行可變調用。很有幫助! :) – riceman89

0

1)你得到的錯誤已經被iharob指出了。 2)我可以理解,在這個頭上= & t_node你想要頭指向你的列表頭。可能需要在文件中的靜態變量能夠使用這個,那麼你可以指向頭部正確

1

既然不能對寫的accepted answer評論@user3629249: 該代碼是比原來更糟糕的(除了它會編譯)。

我建議是這樣的:

node_t *remove_by_value(node_t **head, int val) 
{ 
    node_t *ret = NULL; 

    for (; *head; head = &((*head)->next)) 
    { 
      if ((*head)->val == val) 
      { 
        ret = *head; 
        *head = (*head)->next; 
        break; 
      } 
    } 
    return ret; 
} 

此代碼正確地從列表中移除的開頭,中間和結尾的元素。另外,它給予調用者釋放未鏈接節點的機會。

+0

你會提出什麼建議,而不是一個更清潔的寫作方式?謝謝! – riceman89

+0

我已根據您的要求編輯了我的答案。 – gollum

+0

謝謝!這是很短,優雅,並正常工作。非常感激! – riceman89