题解 | #链表内指定区间反转#
链表内指定区间反转
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) {
if(head == null || m == n) return head;
int cnt = 0;
ListNode vhead, pre, cur, first;
vhead = new ListNode(-1);
vhead.next = head;
pre = vhead;
for(;cnt < m - 1;cnt++) {
pre = pre.next;
}
first = pre.next;
for(;cnt < n - 1;cnt++) {
cur = first.next;
first.next = cur.next;
cur.next = pre.next;
pre.next = cur;
}
return vhead.next;
}
}
腾讯成长空间 5958人发布