reverse_linked_list
1from typing import Optional 2from utils import ListNode 3# @leet start 4 5 6class Solution: 7 def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: 8 """ 9 To reverse a linked list, we want to keep two pointers, `prev` and `curr` 10 where `prev` refers to the previous pointer (or None) and `curr` refers to 11 the head of the linked list. 12 We then advance the linked list by taking the next and storing it in a temporary 13 variable, and then setting prev to curr and curr.next to prev (to reverse the list) 14 next, we set curr to the temporary variable and do that for every variable, 15 and at the end we return the prev pointer, which now holds the reversed list. 16 """ 17 prev = None 18 curr = head 19 while curr: 20 next_temp = curr.next 21 prev = curr 22 curr.next = prev 23 curr = next_temp 24 return prev 25 26 27# @leet end 28 29 30def test(): 31 assert 2 + 2 == 4
class
Solution:
7class Solution: 8 def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: 9 """ 10 To reverse a linked list, we want to keep two pointers, `prev` and `curr` 11 where `prev` refers to the previous pointer (or None) and `curr` refers to 12 the head of the linked list. 13 We then advance the linked list by taking the next and storing it in a temporary 14 variable, and then setting prev to curr and curr.next to prev (to reverse the list) 15 next, we set curr to the temporary variable and do that for every variable, 16 and at the end we return the prev pointer, which now holds the reversed list. 17 """ 18 prev = None 19 curr = head 20 while curr: 21 next_temp = curr.next 22 prev = curr 23 curr.next = prev 24 curr = next_temp 25 return prev
8 def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: 9 """ 10 To reverse a linked list, we want to keep two pointers, `prev` and `curr` 11 where `prev` refers to the previous pointer (or None) and `curr` refers to 12 the head of the linked list. 13 We then advance the linked list by taking the next and storing it in a temporary 14 variable, and then setting prev to curr and curr.next to prev (to reverse the list) 15 next, we set curr to the temporary variable and do that for every variable, 16 and at the end we return the prev pointer, which now holds the reversed list. 17 """ 18 prev = None 19 curr = head 20 while curr: 21 next_temp = curr.next 22 prev = curr 23 curr.next = prev 24 curr = next_temp 25 return prev
To reverse a linked list, we want to keep two pointers, prev and curr
where prev refers to the previous pointer (or None) and curr refers to
the head of the linked list.
We then advance the linked list by taking the next and storing it in a temporary
variable, and then setting prev to curr and curr.next to prev (to reverse the list)
next, we set curr to the temporary variable and do that for every variable,
and at the end we return the prev pointer, which now holds the reversed list.
def
test():