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 :
Sample Output 1 :
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 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) |
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
#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)) |
Comments
Post a Comment
Please give us your valuable feedback