首页 技术 正文
技术 2022年11月18日
0 收藏 453 点赞 4,766 浏览 782 个字

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULL, m = 2 and n =
4,

return 1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

处理这个问题还是挺复杂的。须要考虑非常多边界的測试用例。我整体的思路是先用循环标记m前一个节点和n后边一个节点。把n后边的节点首先作为当前逆转节点的pre,然后循环n-m次完毕所选节点部分的逆序,然后将标记的m节点前一个节点指向逆序后部分的头节点就可以。

要考虑各种特殊情况,另外考虑就可以。

code例如以下:

class Solution {
public:
ListNode *reverseBetween(ListNode *head, int m, int n) {
if(head==NULL || m<0 || n<0)
return head;
if(head->next == NULL || m==n)
return head;
ListNode *head2=NULL,*pre,*cur,*temp=head;
for(int i=0; i<n+1; i++)
{
if(i==m-2)
head2=temp;
else if(i==m-1)
cur=temp;
else if(i==n)
pre=temp;
if(temp!=NULL)
temp = temp->next;
}
for(int i=m;i<n+1;i++)
{
temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
if(m==1)
return pre;
head2->next = pre;
return head;
}
};

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,071
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,549
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,397
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,174
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,809
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,889