美文网首页
25. Reverse Nodes in k-Group 单链表

25. Reverse Nodes in k-Group 单链表

作者: 羲牧 | 来源:发表于2020-05-25 21:16 被阅读0次
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        if head is None or k <= 1:
            return head
        list_length = 0
        //新建空头节点
        real_head = ListNode(0)
        real_head.next = head
        p = real_head.next
        while p:
            list_length += 1
            p = p.next
        round_cnt = list_length // k
        first = real_head
        for i in range(round_cnt):
            p = first.next
            for j in range(1, k):
                //print('i,j,k',i,j,k)
                q = p.next
                p.next = q.next
                q.next = first.next
                first.next = q
            if i == 0:
                real_head = first
            first = p
        return real_head.next            
        ```

相关文章

网友评论

      本文标题:25. Reverse Nodes in k-Group 单链表

      本文链接:https://www.haomeiwen.com/subject/nzysahtx.html