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

原文地址:https://www.cnblogs.com/yunxintryyoubest/p/13463513.html