struct node {
int key;
char value[32];
struct node *next;
};
struct node *list = NULL;
struct node *add(struct node *list, int key, char *value){
struct node *n = malloc(sizeof(struct node));
n->key = key;
strcpy(n->value, value);
n->next = list;
return n;
}
struct node *get(struct node *list, int key){
struct node *n = list;
while((n != NULL) && (n->key != key)){
n = n->next;
}
return (n != NULL && n->key == key) ? n : NULL;
}
int main(void) {
list = add(list, 3000, "Bern");
list = add(list, 4000, "Basel");
list = add(list, 8000, "Zurich");
while (list != NULL) {
printf("Node %s mit Key %d\n", list->value, list->key);
list = list->next;
}
struct node *n = get(list, 4000);
printf("Key is: %d \n", n->key);
}
如果可以在串列中找到它,我想獲得一個指向結構節點的指標。在下面的代碼中,我嘗試列印串列中的節點鍵(代碼中的最后一行),但出現錯誤。有人可以幫幫我嗎?
uj5u.com熱心網友回復:
在這個while回圈之后
while (list != NULL) {
printf("Node %s mit Key %d\n", list->value, list->key);
list = list->next;
}
指標list等于NULL。因此,您可能不再使用它來訪問串列的節點。
例如,您需要使用中間指標
for ( const struct node *current = list; current != NULL; current = current->next )
{
printf("Node %s mit Key %d\n", current->value, current->key);
}
注意這個return陳述句
return (n != NULL && n->key == key) ? n : NULL;
看起來要簡單得多
return n;
而且寫起來會更安全
struct node *n = get(list, 4000);
if ( n ) printf("Key is: %d \n", n->key);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/530140.html
上一篇:常規陣列和指標陣列有什么區別
