知识点
链表,链表反转
解题思路
定义ans虚拟节点,pre节点先跑到left节点前,在循环left到right之间时,让curr指向next的next,这样curr最后.next指向的就是right节点之后,next节点也可以指向pre.next,不会出现互相指向的情况,再跟新pre.next指向next,这样最后pre的next指向的就是right节点,到达反转的目的。
Java题解
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param left int整型 * @param right int整型 * @return ListNode类 */ public ListNode reverseBetween (ListNode head, int left, int right) { // write code here ListNode ans = new ListNode(0); ans.next = head; ListNode pre = ans; for (int i = 1; i < left; i++) { pre = pre.next; } ListNode curr = pre.next; for (int i = left; i < right; i++){ ListNode next = curr.next; curr.next = next.next; next.next = pre.next; pre.next = next; } return ans.next; } }