forked from rupashi97/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverseLinkedList.py
63 lines (45 loc) · 1.17 KB
/
reverseLinkedList.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
'''
Reverse a linked list
Implement 2 ways
1. Iterative
2. Recursive
'''
from typing import Optional
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# Slow iterative
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return head
p = head.next
head.next = None
while p:
q = p.next
p.next = head
head = p
p = q
return head
# Fast iterative
class Solution2:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev = None
while head:
cur = head
head = head.next
cur.next = prev
prev = cur
return prev
# Recursive ~ Slower than iterative
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
def _reverse(prev, node):
if not node:
return prev
n = node.next
node.next = prev
return _reverse(node, n)
return _reverse(None, head)