61. 旋转链表
题目描述
原题
给你一个链表的头节点 head
,旋转链表,将链表每个节点向右移动 k
个位置。
示例 1:
| 输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]
|
示例 2:
| 输入:head = [0,1,2], k = 4
输出:[2,0,1]
|
提示:
- 链表中节点的数目在范围
[0, 500]
内
-100 <= Node.val <= 100
0 <= k <= 2 * 109
题解
| /**
* 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) {
//如果元素为0或者1或者k=0 直接返回
if(head == null || head.next==null || k == 0) return head;
//优先计算链表的长度 因为k可能大于len,所以要取模
ListNode node = head;
int len = 0;
while(node!=null){
len++;
node = node.next;
}
k = k % len;
//取模计算k为0则直接返回
if(k == 0) return head;
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;
}
ListNode next = slow.next;
slow.next = null;
fast.next = head;
return next;
}
}
|