Skip to content

Instantly share code, notes, and snippets.

@mbfisher
Last active December 17, 2024 15:36
Show Gist options
  • Save mbfisher/eebaf4215c948907fcd4efa05b4945e8 to your computer and use it in GitHub Desktop.
Save mbfisher/eebaf4215c948907fcd4efa05b4945e8 to your computer and use it in GitHub Desktop.
Leetcode 206 Reverse Linked List
# https://leetcode.com/problems/reverse-linked-list/description/
# 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]:
if head is None:
return None
if head.next is None:
return head
a = head
b = a.next
a.next = None
while b is not None:
# i = 0
# 1 -> 2 -> 3 -> 4 -> 5
# a b c
# 1 <- 2, 3 -> 4 -> 5
# a b
#
# i = 1
# 1 <- 2, 3 -> 4 -> 5
# a b c
# 1 <- 2 <- 3, 4 -> 5
# a b
#
# i = 2
# 1 <- 2 <- 3, 4 -> 5
# a b c
# 1 <- 2 <- 3 <- 4 5
# a b
#
# i = 3
# 1 <- 2 <- 3 <- 4, 5
# a b
# 1 <- 2 <- 3 <- 4 <- 5
# a
c = b.next
b.next = a
a = b
b = c
return a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment