用于打印链接列表的反向而不实际反转的Python程序
给定一个链表,使用递归函数打印它的反向。例如,如果给定的链表是 1->2->3->4,那么输出应该是 4->3->2->1。
请注意,问题只是关于打印反向。要反转列表本身,请参阅此
难度级别:新手
算法:
printReverse(head)
1. call print reverse for head->next
2. print head->data
执行:
Python3
# Python3 program to print reverse
# of a linked list
# Node class
class Node:
# Constructor to initialize
# the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Recursive function to print
# linked list in reverse order
def printrev(self, temp):
if temp:
self.printrev(temp.next)
print(temp.data, end = ' ')
else:
return
# Function to insert a new node
# at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# Driver code
llist = LinkedList()
llist.push(4)
llist.push(3)
llist.push(2)
llist.push(1)
llist.printrev(llist.head)
# This code is contributed by Vinay Kumar(vinaykumar71)
输出:
4 3 2 1
时间复杂度: O(n)
有关详细信息,请参阅有关打印链接列表的反向而不实际反转的完整文章!