我在准备面试时遇到了这个问题,很想知道它的不同写作方式。我在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;
}
问:用最少的赋值(=)编写代码,这将构建上述内存结构。答:它需要 3 次调用 malloc()。3 个 int 分配 (=) 来设置 int。4 个指针分配给设置头和 3 个下一个字段。稍加一点C语言的聪明和知识,这一切都可以用7个赋值操作(=)来完成。