Print Reverse LinkedList
You have been given a singly linked list of integers. Write a function to print the list in a reverse order.
To explain it further, you need to start printing the data from the tail and move towards the head of the list, printing the head data at the end.
Note :
Input format :
Remember/Constraints :
Output format :
Constraints :
Sample Input 1 :
Sample Output 1 :
Sample Input 2 :
Sample Output 2 :
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node: | |
def __init__(self, data): | |
self.data = data | |
self.next = None | |
def LinkedLists(arr): | |
head = None | |
tail = None | |
if len(arr) < 1: | |
return -1 | |
else: | |
for i in arr: | |
if i == -1: | |
break | |
NewNode = Node(i) | |
if head == None: | |
head = NewNode | |
tail = NewNode | |
else: | |
tail.next = NewNode | |
tail = NewNode | |
return head | |
def printReverse(head) : | |
prev = None | |
current = head | |
while (current is not None): | |
next = current.next | |
current.next = prev | |
prev = current | |
current = next | |
head = prev | |
printLL(head) | |
def printLL(head): | |
while head is not None: | |
print(head.data, end=" ") | |
head = head.next | |
t = int(input()) | |
for i in range(t): | |
arr = list(map(int, input().split())) | |
printReverse(LinkedLists(arr)) |
Comments
Post a Comment
Please give us your valuable feedback