LeetCode206 Reverse Linked List
Author: Stefan Su
Create time: 2022-10-28 00:49:07
Location: New York City, NY, USA
Description Easy
Given the head
of a singly linked list, reverse the list, and return the reversed list.
Example 1
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2
Input: head = [1,2]
Output: [2,1]
Example 3
Input: head = []
Output: []
Constrains
- The number of nodes in the list is the range
[0, 5000]
. -5000 <= Node.val <= 5000
Analysis
Use two indices, cur
and prev
to indicate the two nodes to be operated. In each while loop, use temp
variable to store cur.next
first. And then, set cur.next
to prev
to complete reverse. Finally, update prev
to cur
and cur
to temp
. Attention, the order is really important here. We stop while loop until cur
pointer points to a null pointer.
Solution
- Two indices version.
# 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
"""
# Two index version
cur = head
prev = None
while cur != None:
temp = cur.next
cur.next = prev
prev = cur
cur = temp
return prev
Advance
A linked list can be reversed either iteratively or recursively.
- Recursion version
# 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
"""
# recursion version
def reverse(cur, prev):
if cur == None:
return prev
temp = cur.next
cur.next = prev
return reverse(temp, cur)
return reverse(head, None)
# can also write the reserve function outside of reserveList, but add self to call it
# def reverse(self, cur, prev):
# if cur == None:
# return prev
# temp = cur.next
# cur.next = prev
# return self.reverse(temp, cur)
Hopefully, this blog can inspire you when solving LeetCode206. For any questions, please comment below.