来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/reverse-linked-list-ii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。

解答

  1. /**
  2. * Definition for singly-linked list.
  3. * function ListNode(val, next) {
  4. * this.val = (val===undefined ? 0 : val)
  5. * this.next = (next===undefined ? null : next)
  6. * }
  7. */
  8. /**
  9. * @param {ListNode} head
  10. * @param {number} left
  11. * @param {number} right
  12. * @return {ListNode}
  13. */
  14. const reverseChain = (head) => {
  15. let prev = null;
  16. while (head) {
  17. const next = head.next;
  18. head.next = prev;
  19. prev = head;
  20. head = next;
  21. }
  22. }
  23. var reverseBetween = function(head, left, right) {
  24. const firstNode = new ListNode(null, head);
  25. let curNode = firstNode,
  26. leftStartNode = null,
  27. rightStartNode = null,
  28. leftLastNode = null,
  29. rightLastNode = null,
  30. idx = 0;
  31. while (curNode) {
  32. if ((idx + 1) === left) {
  33. leftStartNode = curNode?.next;
  34. leftLastNode = curNode;
  35. }
  36. if (idx === right) {
  37. rightStartNode = curNode;
  38. rightLastNode = curNode.next;
  39. if (leftStartNode !== null) {
  40. rightStartNode.next = null;
  41. reverseChain(leftStartNode);
  42. leftLastNode.next = rightStartNode;
  43. leftStartNode.next = rightLastNode;
  44. }
  45. }
  46. ++idx;
  47. curNode = curNode.next;
  48. }
  49. return firstNode.next;
  50. };