题解 | #链表内指定区间反转#
链表内指定区间反转
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 if (m == n) { return head; } ListNode tmp = head; ListNode head1 = null; ListNode tail = null; ListNode pre = null; ListNode cur; ListNode next; int index = 1; while (tmp != null) { if (index == m - 1) { head1 = tmp; tmp = tmp.next; } else if (index == m ) { tail = tmp; cur = tmp; next = tmp.next; cur.next = pre; pre = cur; tmp = next; } else if (index > m && index < n) { cur = tmp; next = tmp.next; cur.next = pre; pre = cur; tmp = next; } else if (index == n) { cur = tmp; next = tmp.next; cur.next = pre; tail.next = next; if (head1 != null) { head1.next = cur; } else { head = cur; } } else { tmp = tmp.next; } index++; } return head; } }
- 循环整个链表
- 弄三个变量记住上一个节点,当前节点,下一个节点
- 再弄两个变量记住当前区间范围
- 最后将当前区间连接到原来的链表