您的位置 首页 java

「LeetCode」翻转链表Java题解

# 题目

反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。

说明:

1 ≤ m ≤ n ≤ 链表长度。

示例:

输入: 1->2->3->4->5->NULL, m = 2, n = 4

输出: 1->4->3->2->5->NULL

来源:力扣(LeetCode)

链接:

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

# 代码

 public class DayCode {
    public static void main(String[] args) {
    }
    /**
     * 
     * 时间复杂度 O(n)
     * 空间复杂度 O(1)
     * @param head
     * @param left
     * @param right
     * @return
     */
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode pre = dummy;
        for (int i = 0; i < left - 1; i++) {
            pre = pre.next;
        }
        ListNode rightNode = pre;
        for (int i = 0; i < right - left + 1; i++) {
            rightNode = rightNode.next;
        }
        ListNode leftNode = pre.next;
        ListNode cur = rightNode.next;
        pre.next = null;
        rightNode.next = null;
        reverse(leftNode);
        pre.next = rightNode;
        leftNode.next = cur;
        return dummy.next;
    }
    /**
     * 翻转链表
     *
     * @param root
     */
    public void reverse(ListNode root) {
        ListNode pre = null;
        ListNode current = root;
        while (current != null) {
            ListNode next = current.next;
            current.next = pre;
            pre = current;
            current = next;
        }
    }
}  

# 总结

* 这个题目思路分析,先找到需要翻转的链表区间,然后进行翻转连接。

* 链表翻转题目思路一般简单,需要注意细节,多练习,就能掌握的更好!

* 坚持每日一题,加油!

文章来源:智云一二三科技

文章标题:「LeetCode」翻转链表Java题解

文章地址:https://www.zhihuclub.com/176288.shtml

关于作者: 智云科技

热门文章

网站地图