[Leetcode] 25.Reverse Nodes in k-Group

Problem:

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5

Idea:
这题是24题的一个延伸(24题中k=2)
1. 方法1. 先计算链表长度,便可省去每个reverse group都做长度检查的工作;对于reverse group中的每个元素都翻转一遍,就可以实现最后的倒序翻转。

reference
1)如果提前计算一下整个链表的长度,则在前面几个完整的reverse过程中不再需要做长度检查,大大简化了代码;
2)在reverse的过程中,可以逐个翻转,只要连续翻转k次,即完成了一个reverse。

2.方法2. 可以用递归函数的方法来实现。对于每个reverse group,令其group的首节点为递归函数传入参数head,分别对group都调用一次递归函数即可。因为原传入链表维护在堆中,所以并不会丢失原传入链表的完整性。

Solution 1:

class Solution(object):
    def reverseKGroup(self, head, k):
        count = 0
        tmpNode = head
        while tmpNode != None:
            tmpNode = tmpNode.next
            count += 1
        if count == 0:
            return head
        if k == 1:
            return head
        times = int(count / k)
        preheadNode = ListNode(0)
        preheadNode.next = head
        tmpNode = head.next
        preNode = preheadNode
        lastNode = head
        for counttimes in xrange(0,times):
            for i in xrange(1,k):
                nextNode = tmpNode.next
                tmpNode.next = preNode.next
                lastNode.next = nextNode
                preNode.next = tmpNode
                tmpNode = None if nextNode == None else nextNode
            preNode = lastNode
            lastNode = tmpNode
            tmpNode = None if tmpNode == None else tmpNode.next
        return preheadNode.next
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值