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;
10 
11  int main(int argc, char *argv[])
12  {
13    int key, i;
14    slist_node *head, *temp, *current;
15    head = NULL;
16    temp = NULL;
17    current = NULL;
18    printf ("Single linked list demo application\n");
19    do
20    {
21      printf ("Add a node [y/n] : ");
22      key = getch();
23      if(key == 'y')
24      {
25        temp = (slist_node *)malloc(sizeof(slist_node));
26        if(temp != NULL)
27        {
28          printf ("Value of this node : ");
29          scanf ("%d", &temp->node_value);
30          temp->next = NULL;
31          
32          if(head == NULL)
33          {
34            current = temp;
35            head = temp;
36          }
37          else
38          {
39            current->next = temp;
40            current = temp;
41          }
42        }
43        else
44        {
45          printf ("Memory allocation error!");
46          return -1;
47        }
48 
49      }
50      else
51      {
52        break;
53      }
54 
55    } while (1);
56    current = head;
57    i = 0;
58    printf ("List Contains:\n");
59    while(current)
60    {
61      printf ("Node %d, Value: %d\n", i + 1, current->node_value);
62      i++;
63      current = current->next;
64    }
65    return 0;
66  }

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

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

 Vote 0

Similar topics related to this section

C and Data Structures, Data Structures using array, Linked List, Single Linked list, Doubly Linked list, Circular Linked list, Doubly Circular Linked list, Queue,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan