Linked Lists

Array : 
 
                                 
This given array is contiguous and Linear or in other ways it is sequential.

                                     
                           
This given Singly linked list is also linear .



                                     
This is non - linear because here element 1 is linked to two elements.

Linked List : It is linear but non - contiguous. In this, each element is actually a separate object while all objects are linked together by referenced field. There are two types of linked lists :
  • Singly Linked List
  • Doubly Linked List
Applications :
  • Image viewer
  • Previous and next page in web browser.
  • Music Player
  • DNA molecules etc...

In linked list we can't randomly access any element. It takes O(n) time on average to visit an element by index where n is length of the list.

Operations in Singly Linked List : 
  • Add Operation
  • Delete Operation
  • Search Operation
You can insert a new node or add a new node into the linked list by O(1) complexity. If we have to add node at beginning the steps performed can be :
  • Initialize new node
  • Link new node to our original head node where head node is the node present at the beginning of the linked list.
  •  Assign new node to head.

To delete a node find previous and next of the node you want to delete.
It is easy to find next node but for previous node we have to traverse from the head node. It takes complexity O(n). Always break the connection with the node first and then the next node otherwise we will lost the reference. If we want to remove head node, first we will change head by head = head.next and the follow the same procedure.

In a given linked list, if we want to determine whether it contains the cycle or not , it can be determined by two ways :
  • Hash table
  • Two - pointer Technique
Two pointer technique is more efficient than Hash.

Two - Pointer in Linked List : 
  • If there is no cycle, the fast pointer will stop at the end of the linked list.
  • If there will be a cycle in the linked list, it will catch up or stop along with the slow pointer.
  • Here, for optimal speed, fast pointer speed is twice the slow speed. 


Comments

Popular posts from this blog

Model Evaluation and Selection

Convolutional Neural Networks(Part-4)

Introduction to Machine Learning(Part-4)