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 - II
class 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:

  1. 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.
  2. LinkedList Class:

    • The LinkedList class represents the entire linked list. It contains two main methods:
      • __init__(): Initializes an empty linked list by setting the head attribute to None.
      • print_list(): Traverses the linked list and prints the data of each node.
  3. Creating the Linked List:

    • We create three Node objects: head, second, and third with data values 1, 2, and 3, respectively.
    • We set the next attribute of head to second, and the next attribute of second to third. This creates a linked list with three nodes.
  4. 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 a next attribute of None.
    • For each node, it prints the data value and moves to the next node using the next attribute.

When you run the program, it will print the elements of the linked list: "1 2 3".