92. Reverse Linked List II

栏目: Java · 发布时间: 7年前

内容简介:Reverse a linked list from position m to n. Do it in one-pass.Note: 1 ≤ m ≤ n ≤ length of list.Example:

Reverse a linked list from position m to n. Do it in one-pass.

Note: 1 ≤ m ≤ n ≤ length of list.

Example:

Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL

难度:medium

题目:反转从m到n的链表元素。一次遍历。

思路:记录m及m之前的位置,然后使用头插法。

Runtime: 2 ms, faster than 97.09% of Java online submissions for Reverse Linked List II.

Memory Usage: 36.9 MB, less than 0.95% of Java online submissions for Reverse Linked List II.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (m == n) {
            return head;
        }
        ListNode dummyHead = new ListNode(0);
        dummyHead.next = head;
        ListNode ptr = head, prevMPtr = dummyHead, tailPtr = head;
        for (int i = 1; i <= n; i++) {
            ListNode node = ptr;
            ptr = ptr.next;
            if (i == m - 1) {
                prevMPtr = node;
            } else if (i == m) {
                tailPtr = node;
                node.next = null;
            } else if (i > m) {
                node.next = prevMPtr.next;
                prevMPtr.next = node;
            }
        }
        tailPtr.next = ptr;
        
        return dummyHead.next;
    }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Squid: The Definitive Guide

Squid: The Definitive Guide

Duane Wessels / O'Reilly Media / 2004 / $44.95 US, $65.95 CA, £31.95 UK

Squid is the most popular Web caching software in use today, and it works on a variety of platforms including Linux, FreeBSD, and Windows. Squid improves network performance by reducing the amount of......一起来看看 《Squid: The Definitive Guide》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

MD5 加密
MD5 加密

MD5 加密工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试