• Register
search
Log In

Before moving on to today’s topic, which is how to print a linked list, let’s talk about linked lists. We will be discussing what is a linked list and some of its advantages and then the way of printing a linked list.

 

What is a linked list?

It is a linear data structure like arrays. Linked list elements are linked using pointers and they are not stored at a contiguous location.

 

Advantages

  • Dynamic size

The size of the array is fixed but in the linked list the size is not defined it means it does not store its storage location in the memory when it is compiled. It will occupy space at the run time.

  • Ease of insertion/deletion

Inserting new elements in linked lists is easier than arrays since we have to add more space or memory to the array for inserting the new element.

 

How to print a linked list?

Assume we already have defined the linked list. We are just going to discuss the way of printing the linked list.

The linked list contains NULL at the end. You can use a while loop for printing that and it helps us in going to the next and next.

struct Node
{
     int data;
     struct Node *next;
}

void Print(Node *head)
{
     while(head)
      { cout << head-> data << endl;
        head = head->next;
      }
}


 

posted May 25 in c++ 100 points