题目链接
法一
public ListNode rotateRight(ListNode head, int k) {
if (head == null || head.next == null || k == 0) {
return head;
}
int cnt = 1;
ListNode cur = head;
while (cur.next != null) {
cnt++;
cur = cur.next;
}
k %= cnt;
if (k == 0) {
return head;
}
cur.next = head;
for (int i = 0; i < cnt - k; i++) {
cur = cur.next;
}
ListNode newHead = cur.next;
cur.next = null;
return newHead;
}
本地测试
lay.showTitle(61);
Solution61 sol61 = new Solution61();
ListNode head61 = new ListNode();
int[] nums61 = new int[]{1, 2, 3, 4, 5};
head61 = listOpt.creatListByArray(head61, nums61);
listOpt.showList(head61);
listOpt.showNoHeadList(sol61.rotateRight(head61.next, 2));