Data Structures — Linked List

What is Data Structures ?

Data Structure is a way of organizing the data in such a way that the retrieval and insertion of data is fast. This is the simple definition of DS.

What is Linked List?

Linked list is data structure in which the elements are not stored in contiguous memory location, for example one node may be at address 100023 and the next node may be at 143143. Unlike array in which the elements are stored in a sequence. In the linked list the nodes are connected with each other through a link(address). The node consist of two parts one is data and other one is link part, which contains the address to the next node. The first node’s address is stored in Head.

Linked List Structure

Difference between Array and Linked List.

In a array we can have only one type to elements. i.e. if we use int array, then that array will have only integers. But whereas in linked list we have unordered linked elements.

In array, if we want to access any element we can use index value and directly access that element but in the case of linked list we have to traverse from the head till the last node

In linked list the insertion and deletion is simple , say if i have to delete node 3 then i can delete it and just need to make changes in the previous and next nodes address. Whereas if i delete anything in middle of array i need to reorganize the entire array.

Array size is fixed at time of declaration and the linked list can be expanded as required.

But the linked list consume extra space for having the link part :(

Sample Code — Python

One class to create a node type

class Node:def __init__(self, data):self.data = dataself.next = None

A class to append the data in the linked list…

class LinkedList:def __init__(self):self.Head = Nonedef append(self, val):nn = Node(val)if self.Head == None:self.Head = nnelse:t = self.Headwhile t.next:t = t.nextt.next = nn

To call the linked list class and pass the data,

ll = LinkedList()ll.append(2,3,4,5,6)

Now, there are 5 nodes created in the linked list. We can print the data with the help of below code snippet.

def print_ll(self):if self.Head == None:print("No data in the linked list")curr = self.Headwhile(curr != None):print("The Data is"+curr.data)curr = curr.next

The full source can be found at my Github repo mentioned below, i will be posting about other data structures in my later posts.

Software Engineer. To know more about me check https://lokesh-online.web.app