LeetCode92 反转链表II

题目

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

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

方法

穿针引线法

现找到反转的头节点,然后用常规的反转链表法反转后再连接

  • 时间复杂度:O(n),n为链表节点个数
  • 时间复杂度:O(1)
class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode newHead = new ListNode();
        newHead.next = head;
        ListNode pre = newHead;
        int i = 1;
        while(i<left&&pre!=null){
            pre = pre.next;
            i++;
        }
        ListNode[] res = reverse(pre.next,left,right);
        pre.next = res[0];
        res[1].next = res[2];
        return newHead.next;
    }
    private ListNode[] reverse(ListNode head,int start,int end){
        ListNode pre = head,node = head.next;
        int  i = start;
         while(i<end&&node!=null){
            ListNode next = node.next;  
            node.next = pre;
            pre = node;
            node = next;
            i++;
        }
        return new ListNode[]{pre,head,node};
    }
}

头插法

遍历需要反转的链表节点,将每个节点放入头节点的位置达到反转的效果
头插法首先定义cur为需要反转的头节点,pre为需要反转的前一个节点,这两个节点不变,然后执行以下步骤:

  1. 取next为cur的下一个节点
  2. 将cur指向next的下一个节点
  3. 将next指向pre的下一个节点
  4. 将pre指向next
  • 时间复杂度:O(n),n为链表节点个数
  • 时间复杂度:O(1)
class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode newHead = new ListNode();
        newHead.next = head;
        ListNode pre = newHead;
        for(int i=0;i<left-1;i++){
            pre = pre.next;
        }
        ListNode cur = pre.next,next = cur;
        for(int i=0;i<right-left;i++){
            next = cur.next;
            cur.next = next.next;
            next.next = pre.next;
            pre.next = next;
        }
        return newHead.next;
    }
}
posted @   你也要来一颗长颈鹿吗  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示