zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):092 Reverse Linked List II

    题目来源


    https://leetcode.com/problems/reverse-linked-list-ii/

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

    For example:
    Given 1->2->3->4->5->NULLm = 2 and n = 4,

    return 1->4->3->2->5->NULL.

    Note:
    Given mn satisfy the following condition:
    1 ≤ m ≤ n ≤ length of list.


    题意分析


    Input:一个链表

    Output:翻转后的链表

    Conditions:给定翻转的起始位置和终止位置,翻转链表


    题目思路


    关键是理清变换的思路,注意在链表的操作中,经常设置一个空的头节点。

    代码思路如图(注意哪些在变化,至于旋转了,程序员你懂的)


    AC代码(Python)

     1 # Definition for singly-linked list.
     2 # class ListNode(object):
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.next = None
     6 
     7 class Solution(object):
     8     def reverseBetween(self, head, m, n):
     9         """
    10         :type head: ListNode
    11         :type m: int
    12         :type n: int
    13         :rtype: ListNode
    14         """
    15         if head == None or head.next == None:
    16             return head
    17         newHead = ListNode(0)
    18         newHead.next = head
    19         head1 = newHead
    20         for i in range(m - 1):
    21             head1 = head1.next
    22         p = head1.next
    23         print p.val
    24         for i in range(n - m):
    25             tmp = head1.next
    26             head1.next = p.next
    27             p.next = p.next.next
    28             head1.next.next = tmp
    29             print p.val, head1.val
    30         return newHead.next
    31         
    32                 
  • 相关阅读:
    PHP变量及其操作
    PHP基本语法
    PHP安装与配置
    MySQL安装与配置
    获取一个目录的父目录
    Image控件播放 GIF文件
    保存网页MHT
    注册全局热键
    使用多线程实现打字效果
    Delphi 调用外部程序并等待其运行结束
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5455802.html
Copyright © 2011-2022 走看看