题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
public ListNode reverseBetween (ListNode head, int m, int n) {
// write code here
//设置虚拟头节点
ListNode dummyNode = new ListNode(-1);
dummyNode.next = head;
ListNode pre = dummyNode;
for (int i = 0; i < m - 1; i++) {
pre = pre.next;
}
ListNode end = dummyNode;
for (int i = 0; i < n + 1; i++) {
end = end.next;
}
ListNode cur = pre.next;
pre.next=end;
ListNode Cur_next ;
while(cur!=end){
Cur_next=cur.next;
cur.next=pre.next;
pre.next=cur;
cur=Cur_next;
}
return dummyNode.next;
}
}
和反转链表一样,只是提前确定好首尾节点


腾讯成长空间 5981人发布