50 lines
1.3 KiB
Java
50 lines
1.3 KiB
Java
package com.zerroi.leetcode.Three26;
|
|
|
|
import org.w3c.dom.ls.LSException;
|
|
|
|
|
|
public class RotateRight {
|
|
public static void main(String[] args) {
|
|
ListNode head = ListNode.constructLinkedList(new int[]{1, 2, 3, 4, 5});
|
|
SolutionFirst solutionFirst = new SolutionFirst();
|
|
ListNode node = solutionFirst.rotateRight(head, 2);
|
|
}
|
|
|
|
public static void print(ListNode head) {
|
|
while (head != null) {
|
|
System.out.println("head = " + head.val);
|
|
head = head.next;
|
|
}
|
|
}
|
|
}
|
|
|
|
class SolutionFirst {
|
|
public ListNode rotateRight(ListNode head, int k) {
|
|
// 向右移动k个 可以等价于 将链表后k个节点放到链表头部
|
|
int length = length(head);
|
|
k = k % length;
|
|
if (k == 0) return head;
|
|
ListNode cur = head;
|
|
for (int i = 1; i < length - k; i++) {
|
|
cur = cur.next;
|
|
}
|
|
ListNode temp = cur.next;
|
|
cur.next = null;
|
|
ListNode cur1 = temp;
|
|
while (cur1.next != null) {
|
|
cur1 = cur1.next;
|
|
}
|
|
cur1.next = head;
|
|
return temp;
|
|
}
|
|
|
|
public int length(ListNode head) {
|
|
int count = 0;
|
|
while (head != null) {
|
|
count++;
|
|
head = head.next;
|
|
}
|
|
return count;
|
|
}
|
|
}
|