image.png

思路

image.png

code

  1. public ListNode rotateRight(ListNode head, int k) {
  2. if(head==null||head.next==null) return head; //特殊条件判断
  3. ListNode old_tail = head; //记录原来的尾节点
  4. int n=1; //用来记录元素个数
  5. for(;old_tail.next!=null;n++)
  6. old_tail= old_tail.next; //遍历记录old_tail和n
  7. old_tail.next=head; //形成环
  8. ListNode new_tail = head; //记录新的尾节点
  9. for(int i=0;i<n-k%n-1;i++) //向后遍历n-k次
  10. new_tail=new_tail.next;
  11. ListNode new_head = new_tail.next; //记录新的头结点
  12. new_tail.next=null; //把环断掉
  13. return new_head; //返回新的头结点
  14. }