数値の並びを連結リスト(linked list)構造で表現し、その合計を求めるプログラムを作りました。プログラム中にwhile
ループが1つありますが、これをfor
ループで置き換えたいと考えています。
![](/wp-content/include/images/avatar/teacher/5.png)
どう書き直せばいいか、分かりますか?
main.c
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode {
int value;
struct ListNode *pNext;
} ListNode;
int SumListValues(const ListNode *pNode) {
const ListNode *p = pNode;
int sum = 0;
while (p) {
sum += p->value;
p = p->pNext;
}
return sum;
}
int main(void) {
ListNode node4 = { 40, 0 };
ListNode node3 = { 30, &node4 };
ListNode node2 = { 20, &node3 };
ListNode node1 = { 10, &node2 };
printf("Sum: %d\n", SumListValues(&node1));
return EXIT_SUCCESS;
}
実行結果
Sum: 100
![](/wp-content/include/images/avatar/teacher/1.png)
ここまでいろいろな問題を出してきたけど……
![](/wp-content/include/images/avatar/student/2.png)
はい。
![](/wp-content/include/images/avatar/teacher/2.png)
目的が同じプログラムでも、書き方は1つじゃないっていうことは分かったかしら?
![](/wp-content/include/images/avatar/student/8.png)
もちろん!正解はいくつもあるってことですよね。
![](/wp-content/include/images/avatar/teacher/5.png)
そのとおり!今回は、それをそのまま問題にしてみたわ。
![](/wp-content/include/images/avatar/student/7.png)
えっと。つまり、別の正解を考えるってことですか?
![](/wp-content/include/images/avatar/teacher/4.png)
そういうこと!……まず、連結リストは分かる?
![](/wp-content/include/images/avatar/student/6.png)
たしか、「数珠つなぎ」になってるデータ構造だったと思います。
![](/wp-content/include/images/avatar/teacher/3.png)
そうね。一つ一つの「数珠」にあたる部分を「ノード(node)」というのだけど……
![](/wp-content/include/images/avatar/student/3.png)
あ、はい。プログラム中にありますね。
![](/wp-content/include/images/avatar/student/7.png)
ここにノードが4つあって、それぞれに数値が入ってる……
ListNode node4 = { 40, 0 };
ListNode node3 = { 30, &node4 };
ListNode node2 = { 20, &node3 };
ListNode node1 = { 10, &node2 };
![](/wp-content/include/images/avatar/teacher/5.png)
10
、20
、30
、40
っていう数値の並びになっているわね。
![](/wp-content/include/images/avatar/student/11.png)
それって、
node1
、node2
、node3
、node4
の順番でつながってるってことですか?
![](/wp-content/include/images/avatar/teacher/2.png)
そうよ。ノードの構造体を見れば分かると思うけど。
![](/wp-content/include/images/avatar/student/7.png)
構造体は……これか。
typedef struct ListNode {
int value;
struct ListNode *pNext;
} ListNode;
![](/wp-content/include/images/avatar/student/6.png)
数値を
value
に格納しつつ、pNext
がポインタだから、これで次のノードにつながるんですね!
![](/wp-content/include/images/avatar/teacher/4.png)
うん。そうやってできる「数珠つなぎ」が、連結リスト構造ね。
![](/wp-content/include/images/avatar/student/4.png)
なるほど〜!
![](/wp-content/include/images/avatar/teacher/1.png)
さてさて。ここまで分かったら、問題にとりかかれるんじゃないかしら?
![](/wp-content/include/images/avatar/student/11.png)
おっと、そうでした。
![](/wp-content/include/images/avatar/student/7.png)
while
が使われているのは、この関数か……
int SumListValues(const ListNode *pNode) {
const ListNode *p = pNode;
int sum = 0;
while (p) {
sum += p->value;
p = p->pNext;
}
return sum;
}
![](/wp-content/include/images/avatar/teacher/3.png)
このループをよく見て、
for
で書く場合の正解を考えてみてね。
![](/wp-content/include/images/avatar/student/3.png)
はーい。やってみます!
![](/wp-content/include/images/avatar/teacher/7.png)
ループの条件になっている変数に注目してみましょう!