在国内做跨境电商怎么上外国网站,关键词排名优化公司哪家好,设计网站页面要多少钱,苏州网站推广找苏州梦易行一、题目描述
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left < right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
示例 1: 输入:head [1,2,3,4,5], left 2, right 4 输出&…
一、题目描述
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
示例 1:
输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]
示例 2:
输入:head = [5], left = 1, right = 1
输出:[5]
提示:
链表中节点数目为 n
1 <= n <= 500
-500 <= Node.val <= 500
1 <= left <= right <= n
进阶: 你可以使用一趟扫描完成反转吗?
二、解题思路
我们以下图中黄色区域的链表反转为例。
使用No.206 反转链表的解法,反转 left 到 right 部分以后,再拼接起来。我们还需要记录 left 的前一个节点,和 right 的后一个节点。如图所示:
三、代码
/*** 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) {if(left==right){return head;}int index=0;ListNode* rs=head;ListNode* pre;if(left>1){while((head!=nullptr)&&(index<left-1)){pre=head;head=head->next;index++;}ListNode* p1=pre;ListNode* current=head;ListNode* nextNode=current->next;while((current!=nullptr)&&(index<=right-1)){nextNode=current->next;current->next=pre;//反转pre=current;current=nextNode;index++;}p1->next=pre;head->next=nextNode;return rs;}else{ListNode* current=head;ListNode* nextNode=current->next;while((current!=nullptr)&&(index<=right-1)){nextNode=current->next;current->next=pre;//反转pre=current;current=nextNode;index++;}head->next=nextNode;return pre;}}
};
四、复杂度分析
时间复杂度:O(N),其中 N 是链表总节点数。最坏情况下,需要遍历整个链表。
空间复杂度:O(1)。只使用到常数个变量。
欢迎关注微信公众号【算法攻城师】