forked from geekcomputers/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram to reverse Linked List( Recursive solution).py
More file actions
65 lines (45 loc) · 1.18 KB
/
Copy pathProgram to reverse Linked List( Recursive solution).py
File metadata and controls
65 lines (45 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from sys import stdin, setrecursionlimit
setrecursionlimit(10**6)
# Following is the Node class already written for the Linked List
class Node:
def __init__(self, data):
self.data = data
self.next = None
def reverseLinkedListRec(head):
if head is None:
return None
if head.next is None:
return head
smallhead = reverseLinkedListRec(head.next)
head.next.next = head
head.next = None
return smallhead
# Taking Input Using Fast I/O
def takeInput():
head = None
tail = None
datas = list(map(int, stdin.readline().rstrip().split(" ")))
i = 0
while (i < len(datas)) and (datas[i] != -1):
data = datas[i]
newNode = Node(data)
if head is None:
head = newNode
tail = newNode
else:
tail.next = newNode
tail = newNode
i += 1
return head
def printLinkedList(head):
while head is not None:
print(head.data, end=" ")
head = head.next
print()
# main
t = int(stdin.readline().rstrip())
while t > 0:
head = takeInput()
newHead = reverseLinkedListRec(head)
printLinkedList(newHead)
t -= 1