-
Notifications
You must be signed in to change notification settings - Fork 5
/
Reverse_Linked_List.py
48 lines (36 loc) · 987 Bytes
/
Reverse_Linked_List.py
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
'''
Done By > Anand Kothari
Question::
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
--------------------------------------
Solution:
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# Simple iteratively without extra space
# class Solution(object):
# def reverseList(self, head):
# prev = None
# curr = head
# while curr!=None :
# temp = curr.next
# curr.next = prev
# prev = curr
# curr = temp
# head = prev
# return (head)
# Recursively
class Solution:
def reverseList(self, head):
if head is None or head.next is None:
return head
p = self.reverseList(head.next)
head.next.next= head
head.next = None # It removes the unwanted pointer
return p