🌗 61. 旋转链表
2022年10月10日
- algorithm
🌗 61. 旋转链表
难度: 🌗
问题描述
解法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
// 思路:
// 求出链表长度,对 k 取余,截断数组,重新拼接
int len = 0;
ListNode cur = head;
while(cur != null) {
len ++;
cur = cur.next;
}
if(len == 0) {
return head;
}
k = k % len;
if(k == 0) {
return head;
}
// k > 0
ListNode fast = head;
ListNode slow = head;
for(int i = 0; i < k; i ++) {
fast = fast.next;
}
while(fast.next != null) {
fast = fast.next;
slow = slow.next;
}
// 截断 slow 和后面的节点
ListNode next = slow.next;
slow.next = null;
fast.next = head;
return next;
}
}