61.旋转链表
方法:
记给定的链表的长度为n,注意当向右移动的次数k>=n时,仅需要向右移动k mod n
次即可,因为每n次移动都会让链表变为原状
将给定的链表连接成环,然后将指定位置断开
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(k==0 || head == null || head.next == null){
return head;
}
int n = 1;
ListNode p = head;
while(p.next != null) {
p = p.next;
n++;
}
if(k % n == 0 ){
return head;
}
p.next = head; //最后一个节点指向头节点,形成一个环形链表
int add = n - k % n;
//找到尾节点
while(add > 0){
p = p.next;
add--;
}
ListNode t = p.next;
p.next = null;
return t;
}
}