码迷,mamicode.com
首页 > 其他好文 > 详细

Reverse Nodes in k-Group

时间:2015-06-28 18:43:59      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:

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

 

 

 

Reverse Nodes in k-Group

标签:

原文地址:http://www.cnblogs.com/lzsjy421/p/4605840.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!