LINKED LIST IN PYTHON MADE EASY

Nkugwa Mark William
2 min readFeb 4, 2023

--

A linked list in Python can be implemented using classes and nodes. Each node in the linked list contains a value and a reference to the next node in the list. To create a linked list, you can create a class called Node that contains two attributes: data to store the value and next to store the reference to the next node. You can also create another class called LinkedList that contains functions to insert, delete, and traverse the list. Here are the main steps to write a linked list in Python:

  1. Create a class Node with two attributes: data and next
  2. Create a class LinkedList with the following functions:
  • __init__: Initializes the linked list with a head node
  • append: Adds a node to the end of the linked list
  • delete: Deletes a node from the linked list
  • print_list: Prints the values in the linked list

3. Use the LinkedList class to create linked list instances and call the functions as needed.

Here’s a basic implementation of a linked list in Python:

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

class LinkedList:
def __init__(self):
self.head = None

def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node

def print_list(self):
curr_node = self.head
while curr_node:
print(curr_node.data)
curr_node = curr_node.next

llist = LinkedList()
llist.append("A")
llist.append("B")
llist.append("C")
llist.print_list()

Follow, Like and share Thank you

--

--

Nkugwa Mark William
Nkugwa Mark William

Written by Nkugwa Mark William

Nkugwa Mark William is a Chemical and Process engineer , entrepreneur, software engineer and a technologists with Apps on google play store and e commerce sites

No responses yet