我试图在链表中找到第n个元素,但不确定为什么我的return语句后这段代码没有退出。该代码可以继续运行更多时间。
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def print(self):
tmp = self.head
while tmp:
print(tmp.data, end=" ")
tmp = tmp.next
print()
def getNthNode(self, ll, n):
if not ll:
return False
if ll.next is not None:
if n > 1:
self.getNthNode(ll.next, n-1)
else:
#print(ll.data)
return ll.data
else:
print("The position doesn't exist.")
if __name__ == '__main__':
llist = LinkedList()
llist.push(1)
llist.push(2)
llist.push(3)
llist.push(4)
llist.push(5)
llist.print()
x = llist.getNthNode(llist.head, 12)
print("The data at given pos is ", x)
这应该在找到元素后立即退出,但没有找到并继续迭代几次