Regina T.

asked • 08/23/21

Solve it in python

2) Implement a recursive algorithm which will print all the elements of a non-dummy headed singly linked linear list in reversed order.

Example: if the linked list contains 10, 20, 30 and 40, the method will print

40

30

20

10

Note: you’ll need a Singly Node class for this code.



You can use the following singly linked list class to execute the code.

class Node:

   def __init__(self, data):

       self.data = data

       self.next = None



class Mylist:

   def __init__(self, lst):

       self.head = None

       for i in lst:

           new_node = Node(i)


           if self.head == None:

               self.head = new_node

           else:

               last = self.head

               while (last.next):

                   last = last.next

               last.next = new_node


   def pr(self):

       print('-------Printing Linked List--------')

       temp = self.head

       while (temp):

           print(temp.data)

           temp = temp.next

       print('------------------------------------')

if __name__ == '__main__':

lst = Mylist([10,20,30,40,50])

Please solve it properly so the code works accordingly.


1 Expert Answer

By:

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.