旋轉鏈表java
思路:spa
把鏈表鏈接爲一個閉合的環,而後從頭計數,到位置剪開code
java:blog
1 class Solution { 2 public ListNode rotateRight(ListNode head, int k) { 3 if(head==null||head.next==null) return head; 4 ListNode copyhead = head; 5 int size=1; 6 while(copyhead.next!=null){ 7 copyhead=copyhead.next; 8 size++; 9 } 10 copyhead.next=head; 11 for(int i=size-k%size;i>1;i--){ 12 head=head.next; 13 } 14 copyhead=head.next; 15 head.next=null; 16 return copyhead; 17 } 18 }