思路:
- 首先先定位需要反转的链表前的节点,和定位链表长度的前节点。
- 把定位到的节点进行分隔
- 分隔出来的节点就是需要反转的链表
- 把链表进行反转
- 然后拼接回去
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(); } } }
本文介绍了一种方法,如何在链表中指定区间进行反转操作,包括定位、分隔、反转链表并最终拼接回原链表的过程。通过实例代码展示了如何使用ListNode类实现链表的区间反转功能。
553

被折叠的 条评论
为什么被折叠?



