#206. Reverse Linked List | LeetCode Python Solution
Problem
LeetCode Problem
- Reverse Linked List
Python 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: Optional[ListNode]) -> Optional[ListNode]:
""" Excalidraw
https://excalidraw.com/#json=UqvQowXkhpfENtThTOs_E,1B3hSOle-aV0zqAwzWQRGA
"""
# Return immediately if the linked list is empty
if head is None:
return head
# Initialize current node pointer 'c' and next node pointer 'n'
c = head
n = c.next
# Make first node point to None
c.next = None
# Loop until next node pointer is None.
while n is not None:
# Save the pointer to next node
tmp = n.next
# Reverse link
n.next = c
# Advance to next pair of nodes
c = n
n = tmp
# 'c' is the new head so point 'head' to it
head = c
return head