92. Reverse Linked List II

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

内容简介: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;
    }
}

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

查看所有标签

猜你喜欢:

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

Boolean Reasoning

Boolean Reasoning

Brown, Frank Markham / 2003-4 / $ 19.15

A systematic treatment of Boolean reasoning, this concise, newly revised edition combines the works of early logicians with recent investigations, including previously unpublished research results. Th......一起来看看 《Boolean Reasoning》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

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

正则表达式在线测试