-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path206.reverse-linked-list.py
More file actions
93 lines (69 loc) · 2.24 KB
/
206.reverse-linked-list.py
File metadata and controls
93 lines (69 loc) · 2.24 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
from typing import Optional
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# Better because while loop goes till last node! Also easier for type checker
class Solution_one:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return None
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev # prev becomes the new head
class Solution_two:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return None
prev = None
while head.next is not None:
next_node = head.next
head.next = prev
prev = head
head = next_node
head.next = prev
return head
class Solution_three:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev = None
current = head
while current is not None:
next = current.next
current.next = prev
prev = current
current = next
return prev
# first attempt at recursive solution
class Solution_four:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head is None:
return None
new_head = None
def _reverseList(node: ListNode) -> ListNode:
nonlocal new_head
if node.next is None:
new_head = node
return node
prev_node = _reverseList(node.next)
prev_node.next = node
return node
node = _reverseList(head)
node.next = None
return new_head
# @leet start
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head is None or head.next is None:
return head
new_head = self.reverseList(head.next)
head.next.next = head
# Need so that the previous first node will at the end point to None
head.next = None
return new_head
# @leet end