Single linked list

Single linked list is the simplest type of list where each node has a next pointer to point to the next node. At first head and tail both is NULL. After addition of one/more nodes the next pointer of last or tail node points to NULL. Elements can be traversed from head to tail direction only. There is no previous pointer thus traversal from tail to head is not possible. This limitation has been eliminated by doubly linked list. We have discussed about doubly linked list in the next section. Find the visual representation of the single linked list in the below figure.

Single linked list - pictorial view

Single Linked list

Single linked list source code

#include <stdio.h>
#include <conio.h>

typedef struct _slist_node
{
  int node_value;
  struct _slist_node * next;

}slist_node;

int main(int argc, char *argv[])
{
  int key, i;
  slist_node *head, *temp, *current;
  head = NULL;
  temp = NULL;
  current = NULL;
  printf ("Single linked list demo application\n");
  do
  {
    printf ("Add a node [y/n] : ");
    key = getch();
    if(key == 'y')
    {
      temp = (slist_node *)malloc(sizeof(slist_node));
      if(temp != NULL)
      {
        printf ("Value of this node : ");
        scanf ("%d", &temp->node_value);
        temp->next = NULL;
        
        if(head == NULL)
        {
          current = temp;
          head = temp;
        }
        else
        {
          current->next = temp;
          current = temp;
        }
      }
      else
      {
        printf ("Memory allocation error!");
        return -1;
      }

    }
    else
    {
      break;
    }

  } while (1);
  current = head;
  i = 0;
  printf ("List Contains:\n");
  while(current)
  {
    printf ("Node %d, Value: %d\n", i + 1, current->node_value);
    i++;
    current = current->next;
  }
  return 0;
}

Output

Single circular linked list demo application
Add a node [y/n] : y
Value of this node : 1
Add a node [y/n] : y
Value of this node : 10
Add a node [y/n] : y
Value of this node : 100
Add a node [y/n] : n
List Contains:
Node 1, Value: 1
Node 2, Value: 10
Node 3, Value: 100

About our authors: Team EQA

You have viewed 1 page out of 252. Your C learning is 0.00% complete. Login to check your learning progress.

#