leetcode-61. 旋转链表

题目

https://leetcode-cn.com/problems/rotate-list/

代码

思路是先计算长度len 取 kn= k % len 的值 如果等于0 直接返回了

不等于0的情况下 让快指针先走kn步 然后slow和fast一起 当fast到尾部时 slow即使需要处理的位置。

/*
 * @lc app=leetcode.cn id=61 lang=java
 *
 * [61] 旋转链表
 */

// @lc code=start
/**
 * 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) {
      
        int len = 0;
        ListNode p = head;
        while(p!=null){
            len=len+1;
            p=p.next;
        }
        if(len==0){
            return null;
        }

        int kn = k%len;
        if(kn==0){
            return head;
        }

        ListNode fast=head;
        ListNode slow=head;

        for(int i=0;i<kn;i++){
            fast=fast.next; 
        }
        
        while(fast.next!=null){
            fast=fast.next;
            slow=slow.next;
        }

        ListNode head2 = slow.next;
        slow.next=null;
        fast.next=head;

        return head2;
    }
}
// @lc code=end


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容