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                 
  • 相关阅读:
    JSON排序
    iOS常用控件尺寸大集合
    Android 平台下Ftp 使用模拟器需要注意的问题
    PhoneGap Html5 App 横竖屏切换自动退出
    加减密 DES
    入学测试题
    黑马程序员——JAVA基础之反射
    黑马程序员——JAVA基础之网络编程
    黑马程序员——JAVA基础之正则表达式,网络爬虫
    黑马程序员——JAVA基础之GUI
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5455802.html
Copyright © 2011-2022 走看看