インタビューの準備をしているときにこの問題に遭遇し、さまざまな書き方を知りたいと思っていました。http://cslibrary.stanford.edu/103/でこれを見つけ、問題をそのまま与えました。
リスト {1,2,3} を作成するコードは次のとおりです。
struct node* BuildOneTwoThree() {
struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;
head = malloc(sizeof(struct node)); // allocate 3 nodes in the heap
second = malloc(sizeof(struct node));
third = malloc(sizeof(struct node));
head->data = 1; // setup first node
head->next = second; // note: pointer assignment rule
second->data = 2; // setup second node
second->next = third;
third->data = 3; // setup third link
third->next = NULL;
// At this point, the linked list referenced by "head"
// matches the list in the drawing.
return head;
}
Q: 上記のメモリ構造を構築する割り当て (=) の数が最も少ないコードを記述してください。A: malloc() を 3 回呼び出す必要があります。int をセットアップするための 3 つの int 割り当て (=)。セットアップ ヘッドと 3 つの次のフィールドへの 4 つのポインターの割り当て。C 言語の少しの賢さと知識があれば、これはすべて 7 つの代入演算 (=) で実行できます。