题解 | #链表内指定区间反转#
链表内指定区间反转
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 res = new ListNode(-1);
res.next = head; //res.next是首元结点
ListNode pre = res; //前序结点
ListNode cur = head; //把cur置为当前结点
for(int i = 1; i<m; i++){
pre = cur;
cur = cur.next;
}
for(int i = m; i<n; i++) //从m到n
{
ListNode tmp = cur.next;
cur.next = tmp.next;
tmp.next = pre.next;
pre.next = tmp;
}
//去掉表头
return res.next;
}
}
查看8道真题和解析
