LeetCode092——反转链表II

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/reverse-linked-list-ii/description/

题目描述:

知识点:链表

思路一:递归实现

本题只是在LeetCode206——反转链表的基础上外加了一个寻找待反转子链表的第一个节点的前一个节点以及最后一个节点的过程而已。根据LeetCode206——反转链表的思路,有递归实现和非递归实现两种方法。

由于涉及到递归,而每一次递归的时间复杂度都是O(1)级别的,因此时间复杂度和空间复杂度都是O(n - m)。

JAVA代码:

public class Solution {

    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = head;
        ListNode cur1 = dummyHead;
        int interval = n - m;
        while(m > 1){
            m--;
            cur1 = cur1.next;
        }
        ListNode cur2 = cur1.next;
        while(interval > 0){
            interval--;
            cur2 = cur2.next;
        }
        ListNode temp1 = cur1.next;
        ListNode temp2 = cur2.next;
        cur2.next = null;
        cur1.next = reverse(temp1);
        temp1.next = temp2;
        return dummyHead.next;
    }

    private ListNode reverse(ListNode head){
        if(head == null || head.next == null){
            return head;
        }
        ListNode newHead = reverse(head.next);
        ListNode temp = head.next;
        temp.next = head;
        head.next = null;
        return newHead;
    }
}

LeetCode解题报告:

思路二:非递归实现

寻找待反转子链表的第一个节点的前一个节点以及最后一个节点的过程与思路一相同,反转链表的过程与LeetCode206——反转链表中的非递归实现相同。

时间复杂度是O(m - n),空间复杂度是O(1)。

JAVA代码:

public class Solution {

    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = head;
        ListNode cur1 = dummyHead;
        int interval = n - m;
        while(m > 1){
            m--;
            cur1 = cur1.next;
        }
        ListNode cur2 = cur1.next;
        while(interval > 0){
            interval--;
            cur2 = cur2.next;
        }
        ListNode temp1 = cur1.next;
        ListNode temp2 = cur2.next;
        cur2.next = null;
        cur1.next = reverse(temp1);
        temp1.next = temp2;
        return dummyHead.next;
    }

    private ListNode reverse(ListNode head){
        if(head == null || head.next == null){
            return head;
        }
        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = head;
        ListNode cur1 = dummyHead;
        ListNode cur2 = dummyHead.next;
        ListNode cur3 = cur2.next;
        while(cur3 != null){
            cur2.next = cur3.next;
            ListNode temp = cur1.next;
            cur1.next = cur3;
            cur3.next = temp;
            cur3 = cur2.next;
        }
        return dummyHead.next;
    }
}

LeetCode解题报告:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值