Reverse a singly linked list.
Iterative Approach
previous
to None
to store the previous node in the reversed list.current
to head
to traverse through the original list.head
of the list.current
is not None
:
next_node
as current.next
to avoid losing the reference to the next node.current.next
pointer to point to previous
.previous
one step forward to current
.current
one step forward to next_node
.previous
will be the new head of the reversed list. Return previous
.next
pointer is adjusted exactly once.# 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 head is empty or has one element
if head is None or head.next is None:
return head
previous = None
current = head
while current:
next_node = current.next # save the next node
current.next = previous # reverse the link
previous = current # move previous one step
current = next_node # move current one step
return previous