给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
示例 1:
输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]
示例 2:
输入:head = [5], left = 1, right = 1
输出:[5]
思路:游标到对应位置之前的一个节点,然后不断的进行逆转
/*** Definition for a singly-linked list.* class ListNode {* public $val = 0;* public $next = null;* function __construct($val = 0, $next = null) {* $this->val = $val;* $this->next = $next;* }* }*/class Solution {/*** @param ListNode $head* @param Integer $left* @param Integer $right* @return ListNode*/function reverseBetween($head, $left, $right) {$preNode = new ListNode(-1);$preNode->next = $head;$pre = $preNode;for($i = 1;$i<$left;$i++){$pre = $pre->next;}$cur = $pre->next;for($j = $left; $j<$right; $j++){$temp = $cur->next;$cur->next = $cur->next->next;$temp->next = $pre->next;$pre->next = $temp;}return $preNode->next;}}
