Linked list is one of the famous data structure that people come across. It is a linear data structure that is stored in memory in non-contagious fashion. One can access elements of a linked list from the start only, unless reference to other element is provided. A basic linked list comprises of node objects where each node has two properties – data and link.
First node of a linked list is represented by a pointer head.
Data is used to store a specific kind of information and link is used to reference next node in the linked list. Properties can be added depending upon the scenario but this is what a native linked list representation looks like.
A linked list can be of following types:
- Single linked list – containing data and pointer to the next node. Last node’s next is null as it doesn’t point to anything
- Doubly linked list – containing data and two pointers – next and previous to reference link to next and previous nodes respectively, of the current node.
- Circular linked list – a variation of single linked list where last node points to the first node instead of null.
- Doubly circular linked list – a variation of circular linked list in which a node stores information about its predecessor and successor nodes.
Python representation of a linked list
A linked list can be easily represented in python using an object to define nodes.
class LinkNode(object): def __init__(self, value): self.data = value self.next = None class LinkedList(object): def __init__(self): self.head = None self.current = None def insert_node(self, value): temp_node = LinkNode(value) if not self.head: self. head = temp_node self.current = temp_node return self.current.next = temp_node self.current = temp_node
Image courtesies:
The post Creating a linked list – Python implementation appeared first on PyJournal.