NULLcheckPt
になるまでループします
これを見ることができます:
O1 --> O2 --> 03 --> ... --> オン --> NULL
したがって、checkPt
null であり、オブジェクトを作成してcheckPt
ポイントする場合は問題ありません。
問題は次のとおりです。現在、On は checkPt を指していません。まだNULLを指しています。(つまり、何も指さないことを意味します)。
したがって、最後のノード(この場合はOn
) までトレースし、新しいオブジェクトを作成して、この lastNode が指すようにする必要があります。
これが私のコード例です:
struct checkPoints *tailPoint = *checkPoint;
while (tailPoint->next != NULL) {
tailPoint = tailPoint->next;
}
struct checkPoints *newPoints = malloc(sizeof (struct checkPoints));
// modify newPoints here
newPoints->next = NULL; // mark it as last node
tail->next = newPoint; // now, mark you last node point to new node. and new node point to end --> NICE
ご覧のとおり、私のコードには単純な別のポイントがあります。私tailPoint->next
は NULL までトレースするので、まだ最後の要素を保持していますが、コードには何もありません。それは大きな違いです。
simonce がコメントしているように、checkPoint が null の場合、私のコードは失敗します: 多くの場合、まだリストに何もありません。したがって、変更されたコードは次のとおりです。
// i'm create newPoint first, because always need new points. this will make the code less redundant.
struct checkPoints *tailPoint = *checkPoint;
struct checkPoints *newPoint = malloc(sizeof (struct checkPoints));
// modified newPoint here
// newPoint always last node, so, it will point to NULL.
newPoint->next = NULL;
if (checkPoint== NULL) {
*checkPoint = newItem; // base on new idea
}
else {
while (tailPoint->next != NULL) {
tailPoint = tailPoint->next;
}
tailPoint->next = newItem; // as upper code, add last node to tailPoint.
}
newItem
assign to checkPoint
(リンクされたリストの最初のノード) とtailPoint
(リンクされたリストの最後のノード)の 2 つのケースの違いに気付くはずです。