Problem : https://leetcode.com/problems/reverse-linked-list/
The recursive 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: ListNode) -> ListNode:
if not head or not head.next:
# do not reverse empty list or single element list
return head
# reverse list starts with the tail element
tail = head.next
new_head = self.reverseList(tail)
# append the previous head to the tail
tail.next = head
head.next = None
# return the new head
return new_head
The iterative 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]:
if not head: return None
pre = head
cur = head.next
while cur:
t = cur.next
cur.next = pre
pre = cur
cur = t
head.next = None
return pre
Edited on 09/07/2021. Add the iterative solution.
No comments:
Post a Comment