Problem
Solution
Iterative:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
prev = None
curr = head
while curr is not None:
nextNode = curr.next
curr.next = prev
prev = curr
curr = nextNode
return prev
Recursive:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return head
result = self.reverseList(head.next)
head.next.next = head
head.next = None
return result
Recursive solution has larger space complexity(O(n)) due to allocating extra space for new linked list on each level.
'CODE > Algorithms & Data Structures' 카테고리의 다른 글
[Coderust] Binary Search on Sorted Array (0) | 2021.10.11 |
---|---|
[LeetCode] Longest Palindromic Substring (0) | 2021.10.11 |
[LeetCode] Minimum Deletions to Make Character Frequencies Unique (0) | 2021.10.03 |
[LeetCode] String to Integer (atoi) (0) | 2021.10.02 |
[LeetCode] Spiral Matrix (0) | 2021.10.02 |