前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LinkedList - 61. Rotate List

LinkedList - 61. Rotate List

作者头像
ppxai
发布2020-09-23 17:21:13
4090
发布2020-09-23 17:21:13
举报
文章被收录于专栏:皮皮星球皮皮星球皮皮星球

61. Rotate List

Given a linked list, rotate the list to the right by k places, where k is non-negative.

Example 1:

Input: 1->2->3->4->5->NULL, k = 2 Output: 4->5->1->2->3->NULL Explanation: rotate 1 steps to the right: 5->1->2->3->4->NULL rotate 2 steps to the right: 4->5->1->2->3->NULL

Example 2:

Input: 0->1->2->NULL, k = 4 Output: 2->0->1->NULL Explanation: rotate 1 steps to the right: 2->0->1->NULL rotate 2 steps to the right: 1->2->0->NULL rotate 3 steps to the right: 0->1->2->NULL rotate 4 steps to the right: 2->0->1->NULL

思路:

题目意思是根据k值旋转链表,这和旋转数组的做法有些不同,也有相同的,旋转数组,依靠的是根据旋转点交换元素,而链表的旋转,只需要首尾相连,把旋转点置空,变成链表尾就可以,所以难点都是寻找旋转的节点,链表长度对k取模之后得到实际真实需要移动的次数,总长度减去这个次数,就能得到该节点位置。

代码: 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 || head.next == null) return head;
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        ListNode fast = dummy, slow = dummy;
        int len; // get list len;
        for (len = 0; fast.next != null; len++) fast = fast.next;
    
        // find rotate node
        for (int i = len - k % len; i > 0; i--) slow = slow.next;
        
        // rotate
        fast.next = dummy.next;
        dummy.next = slow.next;
        slow.next = null;
        
        return dummy.next;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年07月30日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档