反转链表2(区间反转)

题目描述

给你单链表的头指针 head 和两个整数 leftright ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。

解题思路

在需要反转的区间内,每次到一个节点,都把这个节点插入到区间的头部

代码

C++

// 定义节点
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* reverseBetween(ListNode* head, int left, int right) {
    
    
        // 定义虚拟头节点
        ListNode* dummyhead = new ListNode(-1);
        dummyhead->next = head;
        // 下面两行,就让pre指向始终在要反转区间的前一个节点
        ListNode* pre = dummyhead;
        for (int i = 0; i < left - 1; i++) {
    
    
            pre = pre->next;
        }
        // cur指向反转区间的第一个节点,后面不停的更新
        ListNode* cur = pre->next;
        ListNode* next;
        // 区间内反转
        for (int i = 0; i < right - left; i++) {
    
    
            next = cur->next;					// next指向区间内的新节点
            cur->next = next->next;		// 将cur后移
            // next,移动到区间的起始位置
            next->next = pre->next;
            pre->next = next;		
        }
        head = dummyhead->next;
        delete dummyhead;
        return head;
    }
};

猜你喜欢

转载自blog.csdn.net/Sir666888/article/details/126863754
今日推荐