题目:
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.
要将链表中间的数都翻转,显然就将链表分成3部分,将临界的地方都记录下来,遍历一次后再将临界的节点都连接好。
代码如下:
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode instart=null,inend=null,outstart=null,outend=null;
ListNode pre=null;
int k=1;
ListNode cur=head;
while(cur!=null){
if(k==m-1)
outstart=cur;
if(k==n+1)
outend=cur;
if(k==m){
pre=cur;
instart=cur;
}
if(k==n)
inend=cur;
if(k<=n&&k>m){
ListNode next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
k++;
continue ;
}
cur=cur.next;
k++;
}
if(outstart==null){
head=inend;
}else{
outstart.next=inend;
}
if(outend==null){
instart.next=null;
}else{
instart.next=outend;
}
return head;
}
本文介绍了一种链表从位置m到n的区间反转算法,并提供了一个实现该功能的Java代码示例。通过将链表分为三部分并在遍历过程中记录关键节点的方式,在原地完成反转操作。
550

被折叠的 条评论
为什么被折叠?



