728x90
iterative way
# 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:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prev
recursive way
class Solution:
# @param {ListNode} head
# @return {ListNode}
def reverseList(self, head):
return self.reverse_recu(head, None)
def reverse_recu(self, cur, prev):
if not cur:
return prev
nxt = cur.next
cur.next = prev # point backward
prev = cur
cur = nxt
return self.reverse_recu(cur, prev)
www.youtube.com/watch?v=O0By4Zq0OFc
728x90
'Leetcode' 카테고리의 다른 글
[LeetCode] Invert Binary Tree 파이썬(recursion) (0) | 2021.04.05 |
---|---|
[LeetCode] Contains Duplicate II 파이썬 (dict) (0) | 2021.04.05 |
[LeetCode] Isomorphic Strings 파이썬 (0) | 2021.04.05 |
[LeetCode] Count Primes 파이썬 (0) | 2021.04.04 |
[LeetCode] Remove Linked List Elements 파이썬 (linked list) (0) | 2021.04.04 |
댓글