How to print ith node in Linked List in Python

 How to print ith node in Linked List in Python

To print the i-th node in a linked list in Python, you can use a loop to iterate through the list until you reach the desired node. Here is an example of how you might do this:


# Define a Node class

class Node:

  def __init__(self, value, next=None):

    self.value = value

    self.next = next


# Define a LinkedList class

class LinkedList:

  def __init__(self, head=None):

    self.head = head


  def get_node(self, index):

    # Set the current node to the head

    current = self.head


    # Iterate through the list until the desired node is found

    for i in range(index):

      if current:

        current = current.next

      else:

        raise IndexError('List index out of range')


    # Return the value of the node

    return current.value


# Test the LinkedList class

node1 = Node(1)

node2 = Node(2)

node3 = Node(3)

node4 = Node(4)


node1.next = node2

node2.next = node3

node3.next = node4


linked_list = LinkedList(node1)

print(linked_list.get_node(0))  # Output: 1

print(linked_list.get_node(2))  # Output: 3


This approach works by iterating through the list using a loop and returning the value of the ` i`-th node when it is found. If the index is out of range, an IndexError is raised


Post a Comment

0 Comments