思路:
- 首先先定位需要反转的链表前的节点,和定位链表长度的前节点。
- 把定位到的节点进行分隔
- 分隔出来的节点就是需要反转的链表
- 把链表进行反转
- 然后拼接回去
import java.util.List; /** * @author xienl * @description 链表内指定区间反转 * @date 2022/6/6 */ public class Solution { public static void main(String[] args) { Solution solution = new Solution(); ListNode listNode = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5))))); listNode = solution.reverseBetween(listNode, 2, 4); listNode.print(); } public ListNode reverseBetween (ListNode head, int m, int n) { ListNode dummy = new ListNode(); dummy.val = -1; dummy.next = head; ListNode cur = dummy; // 获取反转之前的节点 for (int i = 0; i < m - 1; i++){ cur = cur.next; } // 反转之后的节点 ListNode tail = cur.next; for (int i = 0; i < n - m ; i++){ tail = tail.next; } ListNode next = tail.next; tail.next = null; // 分隔的头节点变成了需要拼接的下一个节点的节点 tail = cur.next; // 需要反转的节点 ListNode transform = revise(cur.next); // 反转之后拼接结果 cur.next = transform; tail.next = next; return dummy.next; } /** * 反转链表 * @param node * @return */ private ListNode revise(ListNode node){ // 创建一个临时的节点,用来返回 ListNode pre = null; while (node != null){ ListNode next = node.next; node.next = pre; pre = node; node = next; } return pre; } } class ListNode { int val; ListNode next = null; public ListNode(){}; public ListNode(int val){ this.val = val; } public ListNode(int val, ListNode next) { this.val = val; this.next = next; } public void print(){ System.out.print(this.val + " "); if (this.next != null){ this.next.print(); } } }