文章目录
https://leetcode.com/problems/rotate-list/
除了AC以外,还实现了一些链表的方法,如fromArray, toString等
public class Main {
public static void main(String[] args) {
ListNode listNode = new Solution().rotateRight(ListNode.fromArray(new int[]{1, 2, 3, 4, 5}), 2);
System.out.println(listNode);
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
static ListNode fromArray(int[] arr) {
ListNode head = new ListNode(arr[0]);
ListNode p = head;
for (int i = 1; i < arr.length; i++) {
p.next = new ListNode(arr[i]);
p = p.next;
}
return head;
}
@Override
public String toString() {
ListNode p = this;
String str = "";
while (p != null) {
str += (p.val);
if (p.next != null) str += ("->");
p = p.next;
}
return str;
}
}
class Solution {
int getLength(ListNode head) {
int cnt = 0;
while (head != null) {
head = head.next;
cnt++;
}
return cnt;
}
public ListNode rotateRight(ListNode head, int k) {
if (head == null) return head;
int length = getLength(head), i = 0;
k = k % length;
if (k == 0) return head;
k = length - k;
ListNode pre = head, p = head, end = head;
while (i < k) {
pre = p;
p = p.next;
end = p;
i++;
}
while (end.next != null)
end = end.next;
end.next = head;
pre.next = null;
return p;
}
}