061 Rotate List 旋转链表
给定一个链表,将链表向右旋转 k 个位置,其中 k 是非负数。
示例:
给定 1->2->3->4->5->NULL 且 k = 2,
返回 4->5->1->2->3->NULL.
详见:https://leetcode.com/problems/rotate-list/description/
Java实现:
/** * 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 len=0; ListNode cur=head; while(cur!=null){ ++len; cur=cur.next; } k%=len; ListNode slow=head; ListNode fast=head; for(int i=0;i<k;++i){ if(fast.next!=null){ fast=fast.next; }else{ return head; } } while(fast.next!=null){ slow=slow.next; fast=fast.next; } fast.next=head; fast=slow.next; slow.next=null; return fast; } }