Instagram
youtube
Facebook
Twitter

Print in Reverse| Linked List

Task(easy)

Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything.

Example

head* refers to the linked list with data values 

1->2->3

Print the following:
3
2
1

Function Description

Complete the reversePrint function in the editor below.

reversePrint has the following parameters:

  • SinglyLinkedListNode pointer head: a reference to the head of the list

Prints

The data values of each node in the reversed list.

Input Format

The first line of input contains t, the number of test cases.

The input of each test case is as follows:

  • The first line contains an integer n, the number of elements in the list.
  • Each of the next n lines contains a data element for a list node.

Constraints

1<=n<=1000
1<=n<=1000, where list[i] is the ith element in the list.

Sample Input

3

5

16

12

4

2

5

3

7

3

9

5

5

1

18

3

13

Sample Output

5

2

4

12

16

9

3

7

13

3

18

1

5

SOLUTION 1

def reversePrint(llist):

    lst = []

    while llist:

        lst.append(llist.data)

        llist = llist.next

    lst = lst[::-1]

    print(*lst, sep="\n")

SOLUTION 2

def reversePrint(llist):

    # Write your code here

    node = llist

    data_ls=[]

    data_ls.append(node.data)

    while node.next is not None:

        node = node.next

        data_ls.append(node.data)

    print('\n'.join(map(str, data_ls[::-1])))

EXPLANATION STEPS

1.Initialize a List: Create an empty list (elements) to store the elements temporarily.

2.Transfer Elements: Pop each element from the stack and append it to the list until the stack is empty.

3.Print Elements in Reverse: Iterate through the list in reverse order and print each element.