Write a program to print out the elements of a singly linked list?
Q.) Write a program to print out the elements of a singly linked list?
Subject: Data Structures - IIclass Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
temp = self.head
while temp:
print(temp.data, end=" ")
temp = temp.next
if __name__ == "__main__":
llist = LinkedList()
llist.head = Node(1)
second = Node(2)
third = Node(3)
llist.head.next = second
second.next = third
llist.print_list()
Explanation:
Node
Class:- The
Node
class represents a single node in the linked list. It contains two attributes:data
: Stores the data or value of the node.next
: Stores the reference to the next node in the linked list.
- The
LinkedList
Class:- The
LinkedList
class represents the entire linked list. It contains two main methods:__init__()
: Initializes an empty linked list by setting thehead
attribute toNone
.print_list()
: Traverses the linked list and prints the data of each node.
- The
Creating the Linked List:
- We create three
Node
objects:head
,second
, andthird
with data values 1, 2, and 3, respectively. - We set the
next
attribute ofhead
tosecond
, and thenext
attribute ofsecond
tothird
. This creates a linked list with three nodes.
- We create three
Printing the Linked List:
- The
print_list()
method is called to print the elements of the linked list. - The method starts at the
head
node and iterates through the linked list until it reaches a node with anext
attribute ofNone
. - For each node, it prints the data value and moves to the next node using the
next
attribute.
- The
When you run the program, it will print the elements of the linked list: "1 2 3".