Simple linked list program in Python

Alinkedlistisalineardatastructurewhereelementsarenotstorednexttoeachotherinmemory.Theelementsinalinkedlistare linkedusingpointers or references. Linked lists are an ordered collection of objects, similar to a normal list. Linked lists stand apart from lists in how they store elements in memory. While regular lists like arrays and slices use a contiguous memory block to store references to their data, linked lists store references, aka pointers as part of each element.

source

A normal list is just a pointer to the first element in the list, and a specific item can be retrieved by providing a memory offset.

A linked list is also just a pointer to the first element in the list, but memory offsets wont do us any good. We need to examine the first elements next pointer to see where the next item is, then we can navigate to it. From there, we can find the next item and so on down the list.

Python singly linked list example

Node Class

First, well build a Node class. The LinkedList class we eventually build will be a list of Nodes.

classNode: def__init__[self,val]: self.val=val self.next=None defset_next[self,node]: self.next=node def__repr__[self]: returnself.val
Code language: Python [python]

Each node has a val data member [the information it stores] and a next data member. The next data member just points to the next Node in the list if there is one, otherwise its None

Linked List Constructor

classLinkedList: def__init__[self]: self.head=None
Code language: Python [python]

The constructor is easy just initialize an empty head pointer. This indicates we now have an empty list.

Iterating over the list

Lets make it easy to iterate over each item in the list using pythons for _ in _ syntax.

def__iter__[self]: node=self.head whilenodeisnotNone: yieldnode node=node.next
Code language: Python [python]

By implementing Pythons __iter__ method, we can now use iteration syntax. For example, for item in linked_list:.

Adding to the linked list

Lets create a way to add items to the tail of the list, the add_to_tail method. It takes a node as input, iterates over the entire list, then adds the given node to the end.

defadd_to_tail[self,node]: ifself.head==None: self.head=node return forcurrent_nodeinself: pass current_node.set_next[node]
Code language: Python [python]

Removing from the linked list

There are other ways to remove items from the list, but for now, and as an example, lets write a remove from head method.

defremove_from_head[self]: ifself.head==None: returnNone temp=self.head self.head=self.head.next returntemp
Code language: Python [python]

remove_from_head removes and returns the first item from the list, assuming one exists.

Printing the linked list

Last but not least, we can implement Pythons __repr__[] method so that we can call print[] directly on a list and control what it printed. Heres a representation I like:

def__repr__[self]: nodes=[] fornodeinself: nodes.append[node.val] return"->".join[nodes]
Code language: Python [python]

This method will print each nodes value in order, with arrows in between. For example, hello -> this -> is -> my -> list.

Using the linked list

linked_list=LinkedList[] linked_list.add_to_tail[Node['john']] linked_list.add_to_tail[Node['sally']] linked_list.add_to_tail[Node['jimmy']] print["ll:", linked_list] first = linked_list.remove_from_head[] print["removed:", first] print["ll:", linked_list]
Code language: Python [python]

Practical Applications of a Linked List

Linked lists are immensely valuable in computer science because they uniquely allow us to add and remove elements anywhere in the list quickly, with a Big-O complexity of just O[1].

Big-O complexity of a linked list

OperationBig-O Complexity
InsertO[1]
DeleteO[1]
IndexO[n]

Because of the fast operations, linked lists are used practically in many different scenarios, including:

  • Stacks
  • Queues
  • Hash maps, to prevent collisions
  • Undo/Redo operations [stack]
  • Appending a song to a playlist
  • To keep items in the same place in memory for performance reasons

Full Linked List Code Sample

classLinkedList: def__init__[self]: self.head=None def__iter__[self]: node=self.head whilenodeisnotNone: yieldnode node=node.next def__repr__[self]: nodes=[] fornodeinself: nodes.append[node.val] return"->".join[nodes] defadd_to_tail[self,node]: ifself.head==None: self.head=node return forcurrent_nodeinself: pass current_node.set_next[node] defremove_from_head[self]: ifself.head==None: returnNone temp=self.head self.head=self.head.next returntemp classNode: def__init__[self,val]: self.val=val self.next=None defset_next[self,node]: self.next=node def__repr__[self]: returnself.val
Code language: Python [python]

Related Reading

  • Writing a Binary Search Tree in Python

Video liên quan

Chủ Đề