leetcode Reverse Linked List

本文介绍了一种高效的方法来反转链表中指定区间的元素。通过一次遍历和常数空间复杂度实现,适用于解决LeetCode等平台上的相关问题。
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *reverseBetween(ListNode *head, int m, int n) {
        if(m == n){
            return head;
        }
        ListNode dummy(-1);
        ListNode* prev = &dummy;
        dummy.next = head;
        ListNode* fast = prev, *slow = prev;
        for(int i = 1; i < m; ++i){ //fast points to the (m-1)-th pointer of the linked list
            fast = fast->next;
        }
        if(fast->next->next == NULL){
            return head;
        }
        ListNode *tail = fast; //tail: (m - 1)-th pointer of the linked list
        ListNode* tmphead = fast->next; //tmphead: m-th pointer of the linked list
        prev = fast; //(m - 1)-th pointer of the linked list
        fast = fast->next; //fast points to the m-th pointer of the linked list
        for(int i = m; i <= n; ++i){
            ListNode* tmpnext = fast->next; //(i + 1)-th pointer of the linked list
            fast->next = prev;
            prev = fast;
            fast = tmpnext;
        }
        //fast: (n + 1)-th pointer of the linked list
        tail->next = prev;
        tmphead->next = fast;
        return dummy.next;
    }
};

(7 ms solution, one pass and O(1) space)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值