avatar

leecode-92-反转链表II

给你单链表的头指针 head 和两个整数 leftright ,其中 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]

提示:

  • 链表中节点数目为 n
  • 1 <= n <= 500
  • -500 <= Node.val <= 500
  • 1 <= left <= right <= n

进阶: 你可以使用一趟扫描完成反转吗?

Related Topics
  • 链表
  • \n
  • 👍 872
  • 👎 0
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    //给你单链表的头指针 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]
    //
    //
    //
    //
    // 提示:
    //
    //
    // 链表中节点数目为 n
    // 1 <= n <= 500
    // -500 <= Node.val <= 500
    // 1 <= left <= right <= n
    //
    //
    //
    //
    // 进阶: 你可以使用一趟扫描完成反转吗?
    // Related Topics 链表
    // 👍 872 👎 0


    //leetcode submit region begin(Prohibit modification and deletion)
    /**
    * 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 dummyNode = new ListNode(-1, head);
    ListNode pre = dummyNode;
    for (int i = 0; i < left - 1; i++) {
    pre = pre.next;
    }
    ListNode cur = pre.next;
    ListNode next;
    for (int i = 0; i < right - left; i++) {
    next = cur.next;
    cur.next = next.next;
    next.next = pre.next;
    pre.next = next;
    }
    return dummyNode.next;
    }
    }
    //leetcode submit region end(Prohibit modification and deletion)
    文章作者: 无知的小狼
    文章链接: https://bytedance.press/2021/04/23/20210401/leecode-92-%E5%8F%8D%E8%BD%AC%E9%93%BE%E8%A1%A8II/
    版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 无知的小狼

    评论