リストノードを定義するための次の構造体があるとします。
struct node {
int data;
struct node* next;
};
そして、私はリストの長さを取得するためにこの関数を持っています:
int Length(struct node* head) {
struct node* current = head;
int count = 0;
while (current != NULL) {
count++;
current = current->next;
}
return count;
}
なぜ私はこれをしたいのですか:struct node* current = head;
頭上で繰り返すのではなく?
だから、なぜこれは大丈夫ではないでしょうか:
int Length(struct node* head) {
int count = 0;
while (head != NULL) {
count++;
head = head->next;
}
return count;
}
長さ関数内に入ると、ヘッドはスコープを失いません。したがって、head = head-> nextを実行しても、関数外では影響を受けませんか?
ありがとう