Course Content
Programming in C
About Lesson

It is illegal for a structure to contain an instance of itself, but it can have a pointer to itself. Let’s look at the following structure for the node of a Linked List.

struct lnode {
  int value;  /* value of the node */
  struct lnode *next;  /* pointer to the next node */
);

Let’s look at following functions that use this struct:

/* Add a node to the end of linked list.
 */
struct lnode *add_last(struct lnode *head, int val)
{
  struct lnode *ptr;
  struct lnode *node = (struct lnode *) malloc(sizeof(struct lnode));
  node->value = val;
  node->next = NULL;
  if (!head)
    return node;
  ptr = head;
  while (ptr->next)
    ptr = ptr->next;
  ptr->next = node;
  return head;
}

/* Remove the first node from a linked list. 
 */
struct lnode *remove_first(struct lnode *head)
{
  if (!head)
    return NULL;
  struct lnode *ptr = head->next;
  free(head);
  return ptr;
}

/* Display the values in the linked list. 
 */
void display(struct lnode *head)
{
  while (head) {
    printf("%d ", head->value);
    head = head->next;
  }
  printf("\n");
}

/* Free up all the nodes in the linked list. 
 */
void cleanup(struct lnode *head)
{
  while (head) {
    head = remove_first(head);   
  }
}
Scroll to Top