Skip to content

Commit 95486d6

Browse files
author
Ankit Agarwal
committed
Added recursive solution to reverse a singly linked list.
1 parent ae7e917 commit 95486d6

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

linkedlist/reverse.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@
33
"""
44

55

6+
#
7+
# Iterative solution
8+
# T(n)- O(n)
9+
#
610
def reverse_list(head):
711
"""
812
:type head: ListNode
@@ -17,3 +21,16 @@ def reverse_list(head):
1721
current.next = prev
1822
prev = current
1923
return prev
24+
25+
#
26+
# Recursive solution
27+
# T(n)- O(n)
28+
#
29+
def reverse_list_recursive(head):
30+
if head is None or head.next is None:
31+
return head
32+
p = head.next
33+
head.next = None
34+
revrest = self.reverse(p)
35+
p.next = head
36+
return revrest

0 commit comments

Comments
 (0)