Starting with Linked Lists

To whoever reading this, I hope i can add something of knowledge here for you to understand and also increase my understanding of the subject as well. Having said that, let's go on to the problem itself.

WHAT ARE LINKED LISTS?

Linked Lists are linear data structures where values are stored in a special way such as they are linked together- from one value to another. Like a Train has bogeys carrying passengers and are connected to each other with links and locks, a linked lists has Values of data as passengers and Pointers as links and locks to connect each other.


Bogey A has an Engine called Head which directs every other bogey after it. In a Linked List you must always know where the position of the Head is to define where values are in a Linked List. After the head are the pointer boxes called as 'Next'. These 'Next' boxes contain information that tells the user where the other bogey is, in this case, B is after A. 

Question : Add an element in the front of a Linked List

Approach : For inserting any new bogey in our train, we need to have 3 things - 

    • A Bogey                (Node) 
    • Passengers           (Data Values)
    • Connecting Link (pointer)

Function :

void push(Node* head, int new_data)

{ Node* new_node= new Node();

   new_node->data= new_data;

   new_node->next= head;

   head= new_node;

}

Here we have defined a Function 'push' with two parameters, a Head pointer and an integer value to store New Data, 

Steps-

  1. We create a new node by calling Node class
  2. We then insert data into the new node
  3. We link the Next pointer of this new node to point to Head, implying we have inserted new node in front of the head
  4. We change the head to the new value, as Head must always be at the beginning!

That's what I coded!

Popular posts from this blog

Finding the Subarrays (Hackerearth)

Palindrome Index (Hackerrank)

Sherlock and Array (Hackerrank)