-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path206.reverse-linked-list.python2.py
More file actions
48 lines (37 loc) · 1.02 KB
/
Copy path206.reverse-linked-list.python2.py
File metadata and controls
48 lines (37 loc) · 1.02 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
# @leet start
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
#
#
# def printList(self):
# current = self
# while current:
# print(current.val, end=" -> ")
# current = current.next
# print("None")
class Solution(object):
def reverseList(self, head):
"""
:type head: Optional[ListNode]
:rtype: Optional[ListNode]
"""
prev = None
curr = head
while curr is not None:
next_node = curr.next # Save next node
curr.next = prev # Reverse the pointer
prev = curr # Move prev forward
curr = next_node # Move curr forward
return prev
# @leet end
head_values = [1, 2, 4, 5]
head = ListNode(val=head_values[0])
current = head
for i in range(1, len(head_values)):
current.next = ListNode(val=head_values[i])
current = current.next
sol = Solution()
print(sol.reverseList(head))