92.反转链表二
给你单链表头指针 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
题解思路
思路总体是比较好理解的,就是边界处理、代码实现比较考究编码功底,题主太菜了,折磨半个下午呜呜呜。
1、创建虚拟头节点指定head
2、遍历链表定位 left和right
3、切割链表
4、反转链表,可借鉴题206
5、拼接链表
c++代码实现
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
if(!head || !head->next ||right==left){
return head;
}
//创建虚拟子节点。锁定头节点,因为有可能头结点会被反转
ListNode *dummyNode = new ListNode(-1);
dummyNode->next=head;
ListNode *newhead=dummyNode;
ListNode *pre = nullptr, *cur;
ListNode *newpre = nullptr,*newcur;
//定位两个坐标位置,
for(int i=1;i<left;i++){
newhead=newhead->next;
}
newcur=newhead;
for(int i=1;i<=right-left+1;i++){
newhead=newhead->next;
}
pre=newhead;
//确定边界点位置 newcur,cur,pre,newpre四个点。
cur=newcur->next;
newpre = pre->next;
//切断链表
newcur->next=nullptr;
pre->next=nullptr;
//反转链表 原题206.反转链表
ListNode *cur1=cur, *pre1=nullptr;
while(cur1){
auto temp=cur1->next;
cur1->next=pre1;
pre1=cur1;
cur1=temp;
}
//拼接链表
newcur->next=pre;
cur->next=newpre;
return dummyNode->next;
}
};
提交记录