LeetCode - 解题笔记 - 206 - Reverse Linked List

Solution 1

0092. Reverse Linked List II 的简化版,默认边界为头和尾,从头到尾进行逆转。

因此可以在此题实现的基础上进行改动,简化判定和后处理(从边界重新连接)的逻辑。

  • 时间复杂度: O ( N ) O(N) O(N),其中 N N N为输入链表的节点个数,完成一次线性遍历
  • 空间复杂度: O ( 1 ) O(1) O(1),仅维护常数个线性变量(若干指针)
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        auto tail = head;
        if (head != nullptr) {
            auto afterTail = head->next;
        
            while (afterTail != nullptr) {
                auto afterAfterTail = afterTail->next;
                afterTail->next = tail;
                tail = afterTail;
                afterTail = afterAfterTail;
            }

            head->next = nullptr;
        }
        
        
        return tail;
    }
};

Solution 2

Solution 1的Python实现

# 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]:
        tail = head
        if head is not None:
            afterTail = head.next
            
            while afterTail is not None:
                afterAfterTail = afterTail.next
                afterTail.next = tail
                tail = afterTail
                afterTail = afterAfterTail
                
            head.next = None
            
        return tail
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值