4.反转指定位置段的链表
题目描述
给你单链表的头指针head和两个整数left和right,其中 left<=right。请你反转从位置left到位置right的链表节点,返回反转后的链表。
题目链接
https://leetcode-cn.com/problems/reverse-linked-list-ii/description/
样例
输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]
输入:head = [5], left = 1, right = 1
输出:[5]
进阶
使用一趟扫描完成
时间复杂度分析
整个链表只遍历了一遍,所以时间复杂度为O(n)
理解
1.需要考虑的是,如果链表中只有两个结点的情况。
2.定义一个虚拟结点,指向头结点
代码
/**
* 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* reverseBetween(ListNode* head, int left, int right) {
ListNode* fictitious = new ListNode(0);
fictitious->next = head;
if (left == right) {
return head;
}
int num = left-1;
ListNode* first = fictitious;
ListNode* last = first->next;
while (num--) {
first = first->next;
last = first->next;
}
int sum = right - left;
ListNode* a = last;
ListNode* b = a->next;
while (sum--) {
ListNode* c = b->next;
b->next = a;
a = b;
b = c;
}
first->next = a;
last->next = b;
return fictitious->next;
}
};
本文来自博客园,作者:jsqup,转载请注明原文链接:https://www.cnblogs.com/jsqup/p/15690226.html