I came across this problem while preparing for an interview and curious to know the diffrent ways it can be written. I found this at http://cslibrary.stanford.edu/103/ and have given the problem as it is.
here is a code to build the list {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: Write the code with the smallest number of assignments (=) which will build the above memory structure. A: It requires 3 calls to malloc(). 3 int assignments (=) to setup the ints. 4 pointer assignments to setup head and the 3 next fields. With a little cleverness and knowledge of the C language, this can all be done with 7 assignment operations (=).
I did it with six assignments. What do I get?
Also, the exercise isn’t very useful. If I wanted to build a linked list from a known set of integers, I’d do something like this:
Then, you can build an arbitrary list with
Here’s another version using a single assignment, inspired by codelogic’s answer:
Finally, I slightly modified MSN’s solution – now, there’s no assignment at all: