您的位置:首页 > Web前端 > Node.js

DAY27:leetcode #25 Reverse Nodes in k-Group

2016-11-28 16:10 330 查看
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


Subscribe to see which companies asked this question
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
from collections import deque

class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if k <= 1:
return head
nodes = deque()
temp = head
pre = head
flag = True
while temp:
nodes.append(temp)
temp = temp.next
if len(nodes) == k:
temp_h = nodes.pop()
temp_t = temp_h
while len(nodes) > 0:
temp_t.next = nodes.pop()
temp_t = temp_t.next
if flag:
head = temp_h
flag = False
pre.next = temp_h
pre = temp_t
temp_t.next = temp
return head

用一个队列存储节点,到达k个统一reverse。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python leetcode