92.反转链表Ⅱ

点击查看代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;

        ListNode pre = dummy;
        for(int i = 1; i <= left-1; i ++) {
            pre=pre.next;
        }

        ListNode cur = pre.next;

        for(int i = 1; i <= right - left ; i ++) {
            ListNode next = cur.next;

            cur.next = cur.next.next;

            next.next = pre.next;
            pre.next = next;
        }

        return dummy.next;
    }
}
posted @ 2026-02-05 11:45  AnoSky  阅读(5)  评论(0)    收藏  举报