原文链接:61. Rotate List
【思路】
1. 将尾指针指向头指针
2. 并将head指针向后移动k = count – k % count - 1位,phead = head.next就是新链表的头指针
3. 将head.next置空,并返回phead
public ListNode rotateRight(ListNode head, int k) {
if (head == null) return head;
ListNode phead = head;
int count = 1;
while (phead.next != null) {
count++;
phead = phead.next;
}
k = count - k % count - 1;
phead.next = head;
while (k-- > 0)
head = head.next;
phead = head.next;
head.next = null;
return phead;
}
230 / 230 test cases passed. Runtime: 1 ms Your runtime beats 14.33% of javasubmissions.
欢迎优化!
本文介绍了一种链表旋转算法的实现方法,通过调整尾指针和头指针的位置来完成链表的旋转,同时提供了完整的Java代码实现及测试结果。
7619

被折叠的 条评论
为什么被折叠?



