给你一个链表的头节点 head
,旋转链表,将链表每个节点向右移动 k
个位置。
示例 1:
输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]
示例 2:
输入:head = [0,1,2], k = 4
输出:[2,0,1]
提示:
- 链表中节点的数目在范围
[0, 500]
内 -100 <= Node.val <= 100
0 <= k <= 2 * 109
代码:
# @lc app=leetcode.cn id=61 lang=python3
#
# [61] 旋转链表
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
def lenlink(head):
i=0
while head != None:
head=head.next
i=i+1
return i
lens=lenlink(head)
if lens==0:
return head
k=k%(lens)
newlist=ListNode(0,None)
newcur=newlist
cur1 = head
cur2 = head
for i in range(lens-k):
cur1=cur1.next
#print(cur1.val)
for i in range(lens):
if i < k:
newcur.val= cur1.val
print(newcur.val)
cur1=cur1.next
newcur.next=ListNode(0,None)
newcur=newcur.next
else:
newcur.val= cur2.val
#print(cur2.val)
cur2=cur2.next
if i<lens-1:
newcur.next=ListNode(0,None)
newcur=newcur.next
return newlist