Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

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:

image

In 2]: class Node: def _init__(self, data): self.data = data self.next = None def print_linkedlist_spl(head): #YOUR CODE pass def 11(arr): if len(arr)==0: return None head last = head for data in arr[1:]: Node (arr[0]) last.next Node (data) last last.next return head # Main # Read the Link List elements including -1 from sys import setrecursionlimit setrecursionlimit (10000) arr=list(int (i) for i in input().strip().split(' ')) # Create a Linked List after removing -1 from list 1 = 11(arr[:-1]) print_linkedlist_spl(1)

Step by Step Solution

3.33 Rating (159 Votes )

There are 3 Steps involved in it

Step: 1

Pytho... blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Introduction to Algorithms

Authors: Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest

3rd edition

978-0262033848

More Books

Students also viewed these Programming questions

Question

How is ????0 different from ????0?

Answered: 1 week ago