LINKED LIST IN PYTHON MADE EASY
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:
- Create a class
Node
with two attributes:data
andnext
- Create a class
LinkedList
with the following functions:
__init__
: Initializes the linked list with a head nodeappend
: Adds a node to the end of the linked listdelete
: Deletes a node from the linked listprint_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