Posts

Showing posts from June, 2023

Python Data Structures - Linked List - Part 3 - Create and Insert Node into a Linked List

Image
  # Singly linked list # Code has 2 parts # 1) Node part # 2) Linked list part # Adding node to end of the list # Creating class for Node class Node :     # Creating initializer function to invoke attributes and methods in it when an object is created.     def __init__ ( self , value ):         self . value = value ; # Assigning value to the Node.         self . next = None ; # Setting next address as None - Default # Creating class for Linked List class LinkedList :     # Creating initializer function to create a link with HEAD and TAIL to NONE     def __init__ ( self ):         self . head = None ;         self . tail = None ;     # Creating a add_link function to insert a node into Linked List     def add_link ( self , value ):         # Creating object to call Node class         new...

Python Data Structures - Linked List - Part 2

Image
 Let's see how to insert a node into a singly linked list diagrammatically: Here is my singly linked list with 2 nodes. The Linked list starts with HEAD -> Hold the address of the next node -> 001 -> Address of node1 -> Node1 holds the address of Node2 -> Node2 is the last node in the linked list and it has NULL reference. Now, Let's insert a node called "Node3" at the beginning of the linked list. So, When we add a node at the beginning of the list: 1) Make sure the HEAD is updated to point at the new node address (003). 2) New node holds the reference to the previous HEAD node (001). HEAD (003) -> Node 3 refers to 001 -> Node 1 refers to 002 -> Node 2 is NULL. What happens when the node is added to the end of the list: Let's add Node 4 to the end of the list: This is going to be straightforward. Update the previous last node pointing to the address of the new node (004) and the new node pointing to NULL as it is the last node of the list.

Python Data Structures - Linked List - Part 1

Image
  Linked List: A linked list is a form of a collection of data. Data does not have to be in any order. A linked list comprises independent nodes (data + links). Each node contains a link to the next node in the link. Imagine a linked list of a train car. How the linked list is different from the list/array? 1) List/Array uses the index to fetch the elements. 2) List/Array stores the element in a continuous memory location. Below is the linked list. Type of linked list: Single linked list: Each node holds data and references to the next node in the list. Reference is the memory location/address of the node. Node 1 holds the address of Node 2 and it goes on until the tail of the linked list. This type of linked list provides the ability to add and remove nodes in run time. Circular linked list: Reference of the last node points to the address of the first node in the linked list and it creates a circle. This is used in multiple-player games. Circular double linked lis...