Reverse Linked List

Problem Id: 206 Difficulty: Easy Tag: Linked List


Intuition

Simply use 2 pointers, prev and curr. Each time first do a reverst for current node and then go a forward step.

Solution


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        prev = None
        curr = head

        while curr:
            tmp = curr.next
            curr.next = prev
            prev = curr
            curr = tmp

        return prev