Answers on building a linked list in C

  1. Which way round does the example given cause items to be printed out?
    In the reverse order to that in which they are entered. This is a stack or last in first out (LIFO queue.

  2. Modify it to store items so that they are printed out in the reverse order to this.
    The following program shows how a simple, linear linked list can be constructed in C, using dynamic memory allocation and pointers.
    #include<stdlib.h>
    #include<stdio.h>
    
    struct list_el {
       int val;
       struct list_el * next;
    };
    
    typedef struct list_el * item;
    
    void main() {
       item  curr,  head = NULL,  tail = NULL;
       int i;
    
       head = NULL;
    
       for(i=1;i<=10;i++) {
          curr = (item) malloc(sizeof(item));
          curr->val = i;
          curr->next  = tail;
          tail = curr;
    	  if (!head) head = curr;
       }
    
       curr = head;
    
       while(curr) {
          printf("%d\n", curr->val);
          curr = curr->next ;
       }
    }
    
    Plain text version to compile.

Back to the questions.


Back to note on linked lists.