int Count(struct node* head, int searchFor) {
struct node* current = head;
int count = 0;
while (current != NULL) {
if (current->data == searchFor)
count++;
current = current->next;
}
return count;
}
爲什麼需要聲明當前的struct節點?如果我們使用在參數列表中傳遞的head,我們會得到相同的結果。LinkedList:爲什麼需要聲明新的結構節點當前?如果我使用參數頭進行跟蹤,代碼工作得很好嗎?
int Count(struct node* head, int searchFor) {
int count = 0;
while(head != NULL) {
if (head->data == searchFor) {
count ++;
}
head = head->next;
}
return count;
}
這是什麼概念?這只是乾淨的代碼或其他原因?
這都是語義問題:「頭」和「當前」是兩個不同的概念。 – Medinoc
如果您所做的只是步行節點,則不需要額外的'current'。你可以使用值頭指針而沒有問題(如果你想玩的話,指針應該是const struct node * head),沒有理由將一個熱指針傳遞給一個執行簡單隻讀枚舉的函數)。如果需要保存傳入指針值的原始數據(您的算法不會*演示),顯然需要輔助指針。 – WhozCraig