Reverse LL (Recursive)

Given a linked list, reverse it using recursion.

You don't need to print the elements, just reverse the LL duplicates and return the head of updated LL.

Input format : Linked list elements (separated by space and terminated by -1)`

Sample Input 1 :
1 2 3 4 5 -1
Sample Output 1 :
5 4 3 2 1
class Node:
def __init__(self,data):
self.data=data
self.next=None
def LinkedList(arr):
head=None
tail=None
if len(arr)<1:
return None
else:
for i in arr:
if i==-1:
break
else:
NewNode=Node(i)
if head is None:
head=NewNode
tail=NewNode
else:
tail.next=NewNode
tail=NewNode
return head
def printLL(head):
while head is not None:
print(head.data,end=" ")
head=head.next
print()
def reverseLL(head):
if head is None or head.next is None:
return head,head
smallHead,smallTail=reverseLL(head.next)
smallTail.next=head
head.next=None
return smallHead,head
# Main
from sys import setrecursionlimit
setrecursionlimit(11000)
arr=list(map(int,input().split()))
head,tail=reverseLL(LinkedList(arr))
printLL(head)
#using LL
class Node:
def __init__(self,data):
self.data=data
self.next=None
def LinkedList(arr):
head=None
if len(arr)<1:
return
for i in arr:
if i==-1:
break
else:
NewNode=Node(i)
NewNode.next=head
head=NewNode
return 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()))
printLL(LinkedList(arr))
view raw Reverse LL.py hosted with ❤ by GitHub

Comments

Popular posts from this blog

MySQL Multi Source Master Slave Replication using GTID

Access and modify all the resources of our Wiki.js using WikiJS API

How to setup an Nginx reverse proxy with a SSL certificate in XWIKI