fork download
  1. #include <stdlib.h> //NULL, malloc
  2. #include <stdio.h> //printf
  3. #include <assert.h> //assert
  4.  
  5. typedef struct Node {
  6. int val;
  7. struct Node* next;
  8. } node;
  9.  
  10. node* make_ll(int len){
  11. node head; // Code only populates the next field.
  12. head.next = NULL;
  13. node* cur = &head;
  14. for (int i = 0; i < len; i++) {
  15. cur->next = malloc(sizeof *(cur->next));
  16. assert(cur->next);
  17. cur = cur->next;
  18. cur->val = i;
  19. cur->next = NULL;
  20. }
  21. return head.next;
  22. }
  23.  
  24. void print_ll(const node* head){
  25. const node* cur = head;
  26. while (cur != NULL) {
  27. printf("Node %d @ %p points to %p as next\n",
  28. cur->val, (const void *) cur, (void *) cur->next);
  29. cur = cur->next;
  30. }
  31. }
  32.  
  33. int main(){
  34. node* ll = make_ll(4);
  35. print_ll(ll);
  36. free(ll);
  37. }
Success #stdin #stdout 0s 2292KB
stdin
Standard input is empty
stdout
Node 0 @ 0x8ff2008 points to 0x8ff2018 as next
Node 1 @ 0x8ff2018 points to 0x8ff2028 as next
Node 2 @ 0x8ff2028 points to 0x8ff2038 as next
Node 3 @ 0x8ff2038 points to (nil) as next