/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
public ListNode rotateRight(ListNode head, int n) {
if(n == 0 || head == null || head.next == null)
return head;
int len = 1;
ListNode p = head;
while(p.next != null){
len++;
p = p.next;
}
n = len - n%len;
p.next = head;
for(int i = 0; i < n; i++)
p = p.next;
head = p.next;
p.next = null;
return head;
}
}
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
遍历链表求出链表的长度, 将链表的尾节点与头结点相连,
public class Solution {public ListNode rotateRight(ListNode head, int n) {
if(n == 0 || head == null || head.next == null)
return head;
int len = 1;
ListNode p = head;
while(p.next != null){
len++;
p = p.next;
}
n = len - n%len;
p.next = head;
for(int i = 0; i < n; i++)
p = p.next;
head = p.next;
p.next = null;
return head;
}
}