Linked list is a simple data structure in programming, which obviously is used to store data and retrieve it accordingly. To make it easier to imagine, it is more like a dynamic array in which data elements are linked via pointers (i.e. the present record points to its next record and the next one points to the record that comes after it, this goes on until the end of the structure) rather than being tightly packed. There are two types of linked list:
Linked List in Python:To start with Python, it does not have a linked list library built into it like the classical programming languages. Python does have an inbuilt type list that works as a dynamic array but its operation shouldn’t be confused with a typical function of a linked list. This doesn’t mean one cannot implement a linked list in Python, they can but it will not be straight up. The following methods can be used to implement a linked list in Python since it does not have an inbuilt library for it: Method 1: Using deque() package. Below is the implementation of the linked list: Python3
Output: elements in the linked_list: deque(['first', 'second', 'third']) elements in the linked_list: deque(['first', 'fourth', 'second', 'third']) elements in the linked_list: deque(['first', 'fourth', 'second']) elements in the linked_list: deque(['first', 'second']) When to use deque() as a linked list?
Method 2: Using llist package. The llist is an extension module for CPython providing basic linked list data structures. The type is given below command in your command line: pip install llist Below is the implementation of the linked list: Python3
Output: sllist([first, second, third]) sllistnode(first) sllistnode(third) 3 sllist([first, second, third, fifth, fourth]) sllistnode(first) sllistnode(fourth) 5 sllist([first, second, third, fifth]) sllistnode(first) sllistnode(fifth) 4 sllist([first, third, fifth]) sllistnode(first) sllistnode(fifth) 3 Method 3: Using StructLinks package StructLinks is used to easily Access and visualize different Data structures including Linked lists, Doubly Linked lists, Binary trees, Graphs, Stacks, and Queues. The structlinks.LinkedList and structlinks.DoublyLikedList modules could be used to make linked lists. All the operations that could be performed with a list could also be performed with structlinks.LinkedList class. Click to go to the documentation Type the command in your command line: pip install structlinks Below is the implementation of some methods of the linked list: Python3
Output: [1 -> 10.0 -> string] Elements of list: 1 10.0 string Length of list: 3 Set item: list after setting lst[0] to 10 : [10 -> 10.0 -> string] Append and Insert: list after appending and inserting: [10 -> 0.0 -> 10 -> string -> another string] Pop and Remove: list after popping and removing: [0.0 -> string -> another string] |