Reverse Linked List

Problem

Given the head of a singly linked list, reverse the list, and return the reversed list.

Intuition

The problem involves reversing a singly linked list. The idea is to iterate through the list and reverse the direction of the pointers to create a reversed version of the original list.

Approach

Initialize two pointers, prev and current, to None and the head of the linked list, respectively.
Iterate through the linked list using a while loop until current becomes None.
Inside the loop:
Save the next node (nxt) of the current node.
Update the next pointer of the current node to point to the previous node (prev).
Update the prev pointer to the current node.
Update the current pointer to the next node (nxt).
After the loop, the prev pointer will be pointing to the new head of the reversed linked list.
Return the prev pointer.

Complexity

  • Time complexity:

The time complexity is O(n), where n is the number of nodes in the linked list. The algorithm iterates through the entire list once.

  • Space complexity:

The space complexity is O(1) since the solution uses only a constant amount of extra space for the pointers (prev, current, nxt).

Code

# 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]:
        prev , current = None , head

        while current:
            nxt = current.next
            current.next = prev
            prev = current
            current = nxt

        return prev
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值