翻转链表II
2021/7/31 23:08:42
本文主要是介绍翻转链表II,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
详细思路
链表题,别管其他的,先给我画图 画图
class Solution { public: ListNode* reverseBetween(ListNode* head, int left, int right) { ListNode*dummy=new ListNode(0,head); ListNode*pre=dummy,*L=head,*R=dummy,*nex=head; while(right--){ if(--left>0){ pre=pre->next; L=L->next; } nex=nex->next; R=R->next; } pre->next=nullptr; R->next=nullptr; myReverse(L); pre->next=R; L->next=nex; return dummy->next; } void myReverse(ListNode*pre){ if(!pre||!pre->next)return ; ListNode*cur=pre->next; pre->next=nullptr; while(cur->next){ ListNode*nex=cur->next; cur->next=pre; pre=cur; cur=nex; } cur->next=pre; } };踩过的坑 链表题,唯有画图是唯一的方法,图的例子要长,一行代码一张图 头插法一次遍历
画图,先随便花找出方法,然后while内解决第一次和最后
class Solution { public: ListNode* reverseBetween(ListNode* head, int left, int right) { if(left==right)return head; ListNode*dummy=new ListNode(0,head); ListNode*first=dummy,*cur=head->next; for(int i=1;i<=left-1;i++){ first=first->next; cur=cur->next; } ListNode *pre=first->next; for(int i=left+1;i<=right;i++){ ListNode*prepre=first->next,*nex=cur->next; first->next=cur; pre->next=nex; cur->next=prepre; cur=nex; } return dummy->next; } };踩过的坑 常见解决头部方法:dummy
这篇关于翻转链表II的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-28微服务架构中API版本控制的实践
- 2024-09-28AI给的和自己写的Python代码,都无法改变输入框的内容,替换也不行
- 2024-09-27Sentinel配置限流资料:新手入门教程
- 2024-09-27Sentinel配置限流资料详解
- 2024-09-27Sentinel限流资料:新手入门教程
- 2024-09-26Sentinel限流资料入门详解
- 2024-09-26Springboot框架资料:初学者入门教程
- 2024-09-26Springboot框架资料详解:新手入门教程
- 2024-09-26Springboot企业级开发资料:新手入门指南
- 2024-09-26SpringBoot企业级开发资料新手指南