61. Rotate List
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
给定一个链表,向右旋转k个位置,其中k是非负的。
尾部下一个设为NULL即可。使用快慢指针操作,如找链表环等都使用此操作,倒数第k个结点
public ListNode rotateRight(ListNode head, int k) {
if (head == null || k <= 0)
return head;
// 新建一个结点,利于操作
ListNode tmpHead = new ListNode(0);
tmpHead.next = head;
// 使用快慢指针,计算倒数节点数目
ListNode fast = tmpHead;
ListNode slow = tmpHead;
int len = 0;
// 计算链表长度
while (slow.next != null) {
len++;
slow = slow.next;
}
slow = tmpHead;
// 关键,记录k 的有效长度,输入会有k大于链表长度值
k = (len + (k % len)) % len;
// 不需要翻转
if (k == 0)
return tmpHead.next;
// 快指针先走k步
while (--k >= 0)
fast = fast.next;
// 一起走
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
// 重新链接链表,注意置空
tmpHead.next = slow.next;
fast.next = head;
slow.next = null;
return tmpHead.next;
}
本文介绍了一种链表向右旋转k个位置的算法实现。通过一次遍历获取链表长度,并利用快慢指针技巧找到旋转点,最终完成链表的有效旋转。
&spm=1001.2101.3001.5002&articleId=69938918&d=1&t=3&u=f1c5c6944434483ea70a19dd5b0ec4bc)
1384

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



