Reverse Nodes in k-Group

https://oj.leetcode.com/problems/reverse-nodes-in-k-group/

Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified 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

题目:k的倍数项反转,不足k倍数不变

 1 # Definition for singly-linked list.
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution:
 8     # @param {ListNode} head
 9     # @param {integer} k
10     # @return {ListNode}
11     def reverse(self,start,end):
12         newhead=ListNode(0);newhead.next=start
13         while newhead.next!=end:                      #把start后面的数依次放到最前面,直到end出现在最前面(头结点后)为止,实现逆转
14             temp=start.next; start.next=temp.next
15             temp.next=newhead.next; newhead.next=temp #不能写temp.next=start,(1,2,3)-(2,1,3)可以(2,1,3)-(3,2,1)错误
16         return [end,start]
17     def reverseKGroup(self, head, k):
18         if head==None: return None                    #漏掉
19         nhead=ListNode(0); nhead.next=head
20         start=nhead
21         while start.next:
22             end=start
23             for i in range (k-1):                     #for i in range() 
24                 end=end.next
25                 if end.next==None:                    #if在for循环里,走一步一判断,若在k-1步及之前为空,则不足k倍数,不反转直接输出
26                     return nhead.next
27             res=self.reverse(start.next, end.next)
28             start.next=res[0]
29             start=res[1]
30         return nhead.next

 

 

 

posted @ 2015-06-28 17:36  小榛子  阅读(121)  评论(0编辑  收藏  举报