zoukankan      html  css  js  c++  java
  • 450. K组翻转链表

    450. K组翻转链表

    中文English

    给你一个链表以及一个k,将这个链表从头指针开始每k个翻转一下。
    链表元素个数不是k的倍数,最后剩余的不用翻转。

    样例

    Example 1

    Input:
    list = 1->2->3->4->5->null
    k = 2
    Output:
    2->1->4->3->5
    

    Example 2

    Input:
    list = 1->2->3->4->5->null
    k = 3
    Output:
    3->2->1->4->5

    列表翻转 + 生成链表
    """
    Definition of ListNode
    class ListNode(object):
        def __init__(self, val, next=None):
            self.val = val
            self.next = next
    """
    
    class Solution:
        """
        @param head: a ListNode
        @param k: An integer
        @return: a ListNode
        """
        def reverseKGroup(self, head, k):
            # write your code here
            #大致思路:写一个子函数,生成链表
            #另一个写法,全部丢进队列里面,然后翻转,重构  
            queue = []
            dummay = ListNode(0)
            tail = dummay
            
            while head: 
                queue.append(head.val)
                head = head.next
                
            count = len(queue)//k 
            last = len(queue)%k 
            
            array = []
            for i in range(count):
                array.extend(queue[i*k: (i + 1)*k][:: -1])
            
            if (last != 0):
                array.extend(queue[count*k: ])
            
            tail.next = self.getLink(array)
        
            return dummay.next
            
        
        def getLink(self, array):
            new_dummay = ListNode(0)
            tail = new_dummay
            
            for val in array: 
                tail.next = ListNode(val)
                tail = tail.next
    
    
            return new_dummay.next
    
    
  • 相关阅读:
    asp.net mvc 国际化(2) 解决问题
    asp.net mvc 国际化(1) 国际化的基础
    Silverlight自学笔记布局基础
    ASP.NET MVC form验证
    Expression Tree 入门
    JQuery 思维导图
    HashMap的Put方法(二)
    HashMap的构造函数(三)
    HashMap的数据结构(一)
    HashMap之扩容resize(四)
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/13463513.html
Copyright © 2011-2022 走看看