61. Rotate List

Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

Solution:Two Pointers

思路:因为k可以是 > linklist.length的,所以需要知道linklist的长度length找到k = k % length实际rotate的位置。既然求出了length,就不用gap+first/second指针找到
Time Complexity: O(N) Space Complexity: O(N)

Solution Code:

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        // 1  ->  2  ->  3  ->  4  ->  5  ->  null, k = 2
        //              cur           tail
        if(head == null) return null;
        
        // get length of the list
        int length = 1;
        ListNode tail = head;
        while(tail.next != null) {
            tail = tail.next;
            length++;
        }
        // get effective k
        k = k % length; 
        if(k == 0) return head;
        
        // find pos to rotate
        ListNode cur = head;
        for(int i = 0; i < length - k - 1; i++) {
            cur = cur.next;
        }
        // relink
        tail.next = head;
        ListNode new_head = cur.next;
        cur.next = null;
        
        return new_head;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,353评论 0 33
  • 笔者在一首诗中谈到了大手印的三种境界: 大风吹白月,清光满虚空。 扫除物与悟,四海波无生。 扫干净了房间里的灰尘,...
    息羽听雪阅读 3,823评论 0 0
  • 瑞博是一家硅胶制品厂家,硅胶制品的生产可以说是一门复杂的技术活,表面看似简单,但生产工艺比较繁琐。从产品的设计,模...
    森森厉害呢阅读 3,434评论 0 1
  • 现在我们两个人的关系还不如普通人,我不想和你说话,你也不想跟我说话,慢慢的 我开始有点烦你了、 我也开始不把你当做...
    三毛的垃圾桶阅读 1,209评论 0 1