Last active
December 17, 2024 15:36
-
-
Save mbfisher/eebaf4215c948907fcd4efa05b4945e8 to your computer and use it in GitHub Desktop.
Leetcode 206 Reverse Linked List
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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