首页 > 其他 > 详细

450. K组翻转链表

时间:2020-08-09 18:29:33      阅读:91      评论:0      收藏:0      [点我收藏+]

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

450. K组翻转链表

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!