给定一个链表,将链表向右旋转 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;
    }
}

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-13
  • 2021-12-29
  • 2021-11-30
  • 2021-06-29
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-03-03
  • 2021-08-24
  • 2021-10-26
  • 2022-12-23
  • 2022-02-10
  • 2022-12-23
  • 2021-05-13
相关资源
相似解决方案