美文网首页
leetcode-61. 旋转链表

leetcode-61. 旋转链表

作者: sleepforests | 来源:发表于2020-03-25 21:37 被阅读0次

题目

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


相关文章

  • leetcode-61. 旋转链表

    题目 https://leetcode-cn.com/problems/rotate-list/ 代码 思路是先计...

  • leetcode 链表 [C语言]

    21. 合并两个有序链表 合并两个有序链表 61. 旋转链表 (快慢指针) 61. 旋转链表 相关标签 : 链表 ...

  • 链表--旋转链表

    目录[https://www.jianshu.com/p/85e18c21317a] 题号[https://lee...

  • 61. 旋转链表

    61. 旋转链表 问题 给定一个链表,旋转链表,将链表每个节点向右移动 个位置,其中 是非负数。 示例 1: 输...

  • Swift - LeetCode - 旋转链表

    题目 旋转链表 问题: 给定一个链表,旋转链表,将链表每个节点向右移动k个位置,其中k是非负数。 示例: 代码:

  • [LeetCode]61. 旋转链表

    61. 旋转链表给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。示例:输入: 1-...

  • 旋转链表

    给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: 1->2->...

  • 旋转链表

    旋转链表 1.想法: 首先我们可以不每次都找到最后一个元素然后将它作为头结点,即我们得知k后,就可以知道最终的形式...

  • 旋转链表

  • 旋转链表

    题目信息 给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。 输入:head = [...

网友评论

      本文标题:leetcode-61. 旋转链表

      本文链接:https://www.haomeiwen.com/subject/pfkfuhtx.html