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
相关文章推荐
- Leetcode腾讯精选_编号:236 --python
- Leetcode腾讯精选_编号:237 --python
- Leetcode腾讯精选_编号:121 --python
- Leetcode腾讯精选_编号:292 --python
- Leetcode腾讯精选_编号:136 --python
- Leetcode腾讯精选_编号:344 --python
- Leetcode腾讯精选_编号:141 --python
- Leetcode腾讯精选_编号:557 --python
- Leetcode腾讯精选_编号:151 --python
- Leetcode腾讯精选_编号:169 --python
- Leetcode腾讯精选_编号:206 --python
- Leetcode腾讯精选_编号:217 --python
- Leetcode腾讯精选_编号:70 --python
- Leetcode腾讯精选_编号:88 --python
- Leetcode腾讯精选_编号:89 --python
- Leetcode腾讯精选_编号:104 --python
- Leetcode腾讯精选_编号:231 --python
- Leetcode腾讯精选_编号:235 --python
- Leetcode腾讯精选_编号:148 --c++
- Leetcode腾讯精选_编号:160 --java