25. k个一组翻转链表

题目描述

给出一个链表,每 k 个节点一组进行翻转,并返回翻转后的链表。

k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么将最后剩余节点保持原有顺序。

示例 :

给定这个链表:1->2->3->4->5

k = 2 时,应当返回: 2->1->4->3->5

k = 3 时,应当返回: 3->2->1->4->5

说明 :

  • 你的算法只能使用常数的额外空间。
  • 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

我的解法——链表转置(AC)

  • 未ac的时候,我记录每k个数的第一个节点和最后一个节点的下一个节点,这样不好。对于:[1,2,3,4], 2这种case,最后一组转置不过来。后来改成了记录每k个数的第一个节点和最后一个节点
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def get_reverse(self, head, tail):
        res_tail = head
        tail_next = tail.next
        
        if(not head):
            return None, None
        
        res_head = head
        head = res_head.next
        res_head.next = None
        
        while(head != tail_next):
            temp = head.next
            head.next = res_head
            res_head = head
            head = temp
        return res_head, res_tail
        
    def reverseKGroup(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if(not head): 
            return None
        
        res_head = None
        res_tail = None
        
        now_head = head
        now_tail = head
        now_count = 1
        
        while(now_tail):
            if(now_count == k):
                now_tail_next = now_tail.next  # 这里一定要先记录,转置后now_tail.next会变
                
                khead, ktail = self.get_reverse(now_head, now_tail)
                
                if(not res_head):
                    res_head = khead
                else:
                    res_tail.next = khead
                res_tail = ktail
                
                now_count = 1
                now_head = now_tail_next
                now_tail = now_tail_next
            else:
                now_count += 1
                now_tail = now_tail.next

                
            
        if(res_tail):
            res_tail.next = now_head
        if(not res_head):
            return head
        else:
            return res_head