61. 旋轉連結串列
阿新 • • 發佈:2020-10-16
給定一個連結串列,旋轉連結串列,將連結串列每個節點向右移動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
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/rotate-list
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode:if not head:return head res=head nodes=[] while res: nodes.append(res.val) res=res.next l=len(nodes) k%=l k=l-k nodes=nodes[k:]+nodes[:k] i=0 res=head while res: res.val=nodes[i] res=res.next i+=1 return head
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: if not head:return head cur=head l=1 while cur.next: cur=cur.next l+=1 k=l-(k%l) tail=cur tail.next=head for i in range(k): tail=tail.next start=tail.next tail.next=None return start