61-Rotate-List
0x0 题目详情
0x1 解题思路
0x2 代码实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head==null || k==0){
return head;
}
int length=0;
ListNode ptr=head;
while(ptr!=null){
length++;
ptr=ptr.next;
}
//计算到底需要翻转几步
k=k%length;
if(k==0){
return head;
}
ListNode oldHead=head;
ListNode fast=head;
ListNode slow=head;
while(k>0){
fast=fast.next;
k--;
}
//找到翻转点
while(fast.next!=null){
fast=fast.next;
slow=slow.next;
}
//得到翻转点newHead
ListNode newHead=slow.next;
slow.next=fast.next;
fast.next=oldHead;
return newHead;
}
}0x3 课后总结
Last updated