简体   繁体   中英

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?

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)

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM