LeetCode 92. Reverse Linked List II

简介: 给定一个链表,反转指定的子序列.

image.png


Description



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


描述



  • 给定一个链表,反转指定的子序列.


# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2018-12-26 11:44:18
# @Last Modified by:   何睿
# @Last Modified time: 2018-12-26 13:36:47
class ListNode():
    def __init__(self, x):
        self.val = x
        self.next = None
class Solution:
    def reverseBetween(self, head, m, n):
        """
        :type head: ListNode
        :type m: int
        :type n: int
        :rtype: ListNode
        """
        # 需要交换的次数
        move, reverse = m-1, n-m
        # pre初始化指向第一个被换节点的前一个节点,point初始化为第一个被换节点
        # 声明一个辅助头节点
        res = ListNode(0)
        pre, point = res, head
        pre.next = head
        # 把pre,point放到指定位置
        while move > 0:
            pre = pre.next
            point = point.next
            move -= 1
        # 需要交换的次数
        while reverse:
            temp = point.next
            point.next = temp.next
            temp.next = pre.next
            pre.next = temp
            reverse -= 1
        return res.next


源代码文件在这里.


目录
相关文章
|
7月前
|
Java
Leetcode 114. Flatten Binary Tree to Linked List
思路也很简单,先把root的左子树(如有)变成单链表 leftlinkedlist,把root的右子树(如有)变成单链表 rightlinkedlist,再把root的右节点变成leftlikedlist,再把rightlinkedlist接到leftlinkedlist后面,代码如下。
24 1
|
7月前
|
C++
Leetcode Copy List with Random Pointer(面试题推荐)
给大家推荐一道leetcode上的面试题,这道题的具体讲解在《剑指offer》的P149页有思路讲解,如果你手头有这本书,建议翻阅。
31 0
|
7月前
Leetcode 19.Remove Nth Node From End of List
删除单链表中的倒数第n个节点,链表中删除节点很简单,但这道题你得先知道要删除哪个节点。在我的解法中,我先采用计数的方式来确定删除第几个节点。另外我在头节点之前额外加了一个节点,这样是为了把删除头节点的特殊情况转换为一般情况,代码如下。
24 0
|
1月前
|
大数据 Java 程序员
「LeetCode合集」链表(List)及经典问题
「LeetCode合集」链表(List)及经典问题
34 0
LeetCode 141. 环形链表 Linked List Cycle
LeetCode 141. 环形链表 Linked List Cycle
LeetCode 237. 删除链表中的节点 Delete Node in a Linked List
LeetCode 237. 删除链表中的节点 Delete Node in a Linked List
LeetCode Contest 178-1367. 二叉树中的列表 Linked List in Binary Tree
LeetCode Contest 178-1367. 二叉树中的列表 Linked List in Binary Tree
LeetCode 382. Linked List Random Node
给定一个单链表,随机选择链表的一个节点,并返回相应的节点值。保证每个节点被选的概率一样。
51 0
LeetCode 382. Linked List Random Node
|
索引
LeetCode 345. Reverse Vowels of a String
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
58 0
LeetCode 345. Reverse Vowels of a String
|
机器学习/深度学习 NoSQL
LeetCode 344. Reverse String
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。 不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
75 0
LeetCode 344. Reverse String