zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):025-Reverse Nodes in k-Group

    题目来源:

      https://leetcode.com/problems/reverse-nodes-in-k-group/


    题意分析:

      这道题目和上一题目类似,输入一个链表和一个整型k。每k个翻转一下。不能更改链表的值。


    题目思路:

      这道题目为了更加直观,先写一个翻转链表的函数。接下来就是链表操作。


    代码(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 class Solution(object):
     7     def reverse(self,start,end):
     8         nhead = ListNode(0)
     9         nhead.next = start
    10         while nhead.next != end:
    11             tmp = start.next
    12             start.next = tmp.next
    13             tmp.next = nhead.next
    14             nhead.next = tmp
    15         return [end,start]
    16     def reverseKGroup(self, head, k):
    17         """
    18         :type head: ListNode
    19         :type k: int
    20         :rtype: ListNode
    21         """
    22         ans = ListNode(0)
    23         if head == None:
    24             return None
    25         ans.next = head
    26         start = ans
    27         while start.next != None:
    28             end = start
    29             i = 0
    30             while i < k - 1:
    31                 end = end.next
    32                 if end.next == None:
    33                     return ans.next
    34                 i += 1
    35             tmp = self.reverse(start.next,end.next)
    36             start.next = tmp[0]
    37             start = tmp[1]
    38         return ans.next
    View Code

    转载请注明出处:http://www.cnblogs.com/chruny/p/4872990.html

  • 相关阅读:
    bash:express:command not found
    Jquery的window.onload实现
    元素的class和id问题
    安装angular-cli
    [(ngModel)]的实现原理
    bodyparser
    git push不用重复输入用户名和密码(解决方案)
    git提交项目到已存在的远程分支
    angular的$filter服务
    网站上如何添加显示favicon
  • 原文地址:https://www.cnblogs.com/chruny/p/4872990.html
Copyright © 2011-2022 走看看