Singly Linked List | Declaration | Traversing | BitsOfCS


A singly linked list consists of elements that are called ‘nodes’. Every element contains data and a link to the next element in the linked list. Singly linked list contains a number of elements that are linked sequentially with the help of pointers. These elements or nodes are generally self referential structures. When a structure is pointing to the structure of the same type, then it is called ‘self referential structure’. 

Example– 

Declaring a Singly Linked List:

Now we know that we can implement a linked list using self referential structure. Because self referential structure is a structure that contains a data field and a pointer field that points to the next element in the list.

This is how you can use the above definition to create every node in the linked list. The data field stores an integer and *link is a pointer that holds the address of the next node in the linked list.

Traversing a Singly Linked List:

In order to traverse the singly linked list, we can use the ‘head’ pointer and traverse all the nodes of the singly linked list. 

But moving the head pointer is very dangerous, let’s understand why?

So we know, we have only one pointer in the linked list that is ‘head’, that points to the first node of the linked list. During traversing, if we move ‘head’ pointer to the second node then we have no pointer that points to the first node of the singly linked list. So, basically we forgot the address of our first node in the linked list and there is no way to traverse back in the singly linked list. In simple words, we forgot that from where our linked list is starting. 

So, how to tackle this situation?

We can create a ‘temporary’ pointer that has the same address as the ‘head’ pointer and we can use ‘temporary’ pointer to traverse the singly linked list.

Example-

Output-


This is how our linked list looked like:

So, we can move the ‘temp’ pointer to traverse the singly linked list. The above program have two functions-

  1. create_list() : to create the linked list.
  2. traverse() : to traverse the linked list.

If you want to understand the above program then click here !

If you find any problem related to this article, please comment below or contact me here.

manorinfinity Written by:

Complex Problem Solver, Outloud Thinker, An Outstanding Writer, and a very curious human being

Be First to Comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.