Poom Chawalit
Poom Chawalit

Reputation: 3

How to use recursion in python to print Linklist node?

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

def traversal(head):
    current = head
    while current is not None:
        print(current.data)
        current = current.next
    print("End")

This is the normal node printing function. How can I transforms my traversal function to using recursion to print the node?

Upvotes: 0

Views: 33

Answers (2)

J. Bakker
J. Bakker

Reputation: 356

Normally a recursion has an exit check at the beginning

def traversal(node):
    if node is None:
        print("End")
        return

    print(node.data)
    traversal(node.next)

Upvotes: 1

Menglong Li
Menglong Li

Reputation: 2255

Something like this:

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


def traversal(head):
    current = head
    if current is not None:
        print(current.data)
        traversal(current.next)
    else:
        print("End")

Upvotes: 0

Related Questions