線形リスト 練習問題1解答解説

練習問題1: リスト中のノード数を返す関数 int nodeCount(node_t * ndPtr) を作れ.

int nodeCount(node_t *ndPtr)
{
    int ctr;
    ctr = 0;
    while (ndPtr != NULL) {
        ctr ++;
        ndPtr = ndPtr->next; 
    }
    return ctr;
}

ndPtr = ndPtr->nest とすることにより,次々と連結されたノードをたどっていくことは,本文にある listPrint と同じである.違いは, listPrint ではノードにあるデータを表示する部分が, ctr の値を1だけ増やすことに代わっているだけである.