链表指定区间反转解题思路
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c?tpId=295&tqId=654&sourceUrl=%2Fexam%2Foj
题目要求时间复杂度 O(n)O(n),空间复杂度 O(1)
定义三个指针变量*pre,*left,*right;
- pre,找到待反转链表的前一个节点
- left待反转链表的第一个节点
- right待反转链表的第二个节点
链表反转的逻辑如下
- 断开第一个节点和第二个节点
- 改变第一个节点和第二个节点的指向
- 将前一个节点和第二个节点连接
- 更新right
struct ListNode* reverseBetween(struct ListNode* head, int m, int n ) {
if(head==NULL||m=n){
return head;
}
struct ListNode dummy;
dummy.next=head
struct ListNode *pre = &head;
for(int i=1;i<m;i++){
pre = pre->next;
}
struct ListNode *left = pre->next;
struct ListNode *right = lift->next;
for(int i=0;i<n-m;i++){
left->next=right->next;
right->next=pre->next;
pre->next = right;
right= left->next;
}
return dummy.next;
}
查看1道真题和解析
