天天看点

LintCode:K组翻转链表

LintCode:K组翻转链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param head, a ListNode
    # @param k, an integer
    # @return a ListNode
    def reverseKGroup(self, head, k):
        # Write your code here
        if head == None:
            return head
        p1 = head
        p2 = head
        list_len = 
        while p1 != None:
            list_len += 
            p1 = p1.next
        if list_len < k:
            return head
        while p2 != None and list_len >= k:
            list_len -= k
            L = []
            p3 = p2
            for i in range(k):
                L.append(p2.val)
                p2 = p2.next
            L = L[::-]
            for i in range(k):
                p3.val = L[i]
                p3 = p3.next
        return head