您的位置:首页 > 编程语言 > Python开发

Leetcode腾讯精选_编号:61 --python

2019-02-27 12:22 399 查看

给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。

示例 1:

输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL
示例 2:

输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL
解释:
向右旋转 1 步: 2->0->1->NULL
向右旋转 2 步: 1->2->0->NULL
向右旋转 3 步: 0->1->2->NULL
向右旋转 4 步: 2->0->1->NULL

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head:
return None
res=[]
while head:
res.append(head.val)
head=head.next
t=k%len(res)
res=res[-t:]+res[:-t]
head=p=ListNode(None)
for i in res:
head.next=ListNode(i)
head=head.next
return p.next
#p=head
#q=head
#while head.next:
#    head=head.next
#head.next=p
#for i in range(k):
#    p=p.next
#return p
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: