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
链表问题,和上一题Swap Nodes in Pairs类似,只是这道题将输入数字k,表示k个为一组进行反转后输出最终结果
算法很简单,首先判断链表长度是否满足k个,不满足则不需要置换
其次实现对一个列表前k个进行置换的函数
函数返回三个参数,第一个是置换后的链表.第二个是两个置换后需要链接的节点,第三个节点的新的位置
然后递归调用就好了
详细请见代码
1 class Solution(object): 2 3 def confire(self, head, k): 4 if (head == None): 5 return False 6 while (k > 0): 7 if (head== None): 8 return False 9 head = head.next 10 k = k - 1 11 return True 12 13 def reverseKGroup(self, head, k): 14 """ 15 :type head: ListNode 16 :type k: int 17 :rtype: ListNode 18 """ 19 start = ListNode(0) 20 start.next = head 21 node = head 22 em = None 23 if (head == None): 24 return None 25 elif (head.next == None): 26 return head 27 else: 28 if(self.confire(node,k)): 29 st, em, node = self.reverse(node, k) 30 start.next = st 31 while(self.confire(node,k)): 32 s,e,node = self.reverse(node,k) 33 em.next = s 34 em = e 35 if(em!=None): 36 em.next = node 37 return start.next 38 39 def reverse(self,head,k): 40 start = ListNode(0) 41 start.next = head 42 while(head.next!=None and k-1>0 ): 43 temp = head.next 44 head.next = temp.next 45 temp.next = start.next 46 start.next = temp 47 k-=1 48 l = head.next 49 head.next = None 50 return start.next,head,l
浙公网安备 33010602011771号