Print a given linked list in reverse order. You need to print the tail first and head
Question:
Print a given linked list in reverse order. You need to print the tail first and head last. You can't change any pointer in the linked list, just print it in reverse order.Input format : Linked List elements (separated by space and terminated by -1)
Output format : Linked List elements in reverse order (separated by space)
Sample Input 1 :1 2 3 4 5 -1Sample Output 1 :5 4 3 2 1Sample Input 2 :1 2 3 -1Sample Output 2 :3 2 1
Solution:class Node: def __init__(self, data): self.data = data self.next = None
def print_linkedlist_spl(head): # Print a given linked list in reverse order. You need to print the tail # first and head last. You can't change any pointer in the linked list, just # print it in reverse order. # GOOD PROBLEM for RECURSION ############################# # PLEASE ADD YOUR CODE HERE # ############################# pass
def ll(arr): if len(arr)==0: return None head = Node(arr[0]) last = head for data in arr[1:]: last.next = Node(data) last = last.next return head
# Main# Read the link list elements including -1from sys import setrecursionlimitsetrecursionlimit(10000)arr=list(int(i) for i in input().strip().split(' '))# Create a Linked list after removing -1 from listl = ll(arr[:-1])print_linkedlist_spl(l)
Code looks like this in editor:
Introduction to Algorithms
ISBN: 978-0262033848
3rd edition
Authors: Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest