给你单链表的头指针 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]

    思路:游标到对应位置之前的一个节点,然后不断的进行逆转

    1. /**
    2. * Definition for a singly-linked list.
    3. * class ListNode {
    4. * public $val = 0;
    5. * public $next = null;
    6. * function __construct($val = 0, $next = null) {
    7. * $this->val = $val;
    8. * $this->next = $next;
    9. * }
    10. * }
    11. */
    12. class Solution {
    13. /**
    14. * @param ListNode $head
    15. * @param Integer $left
    16. * @param Integer $right
    17. * @return ListNode
    18. */
    19. function reverseBetween($head, $left, $right) {
    20. $preNode = new ListNode(-1);
    21. $preNode->next = $head;
    22. $pre = $preNode;
    23. for($i = 1;$i<$left;$i++){
    24. $pre = $pre->next;
    25. }
    26. $cur = $pre->next;
    27. for($j = $left; $j<$right; $j++){
    28. $temp = $cur->next;
    29. $cur->next = $cur->next->next;
    30. $temp->next = $pre->next;
    31. $pre->next = $temp;
    32. }
    33. return $preNode->next;
    34. }
    35. }

    https://leetcode-cn.com/problems/reverse-linked-list-ii/