LeetCode刷题笔录 Rotate List

26 篇文章 0 订阅
13 篇文章 0 订阅

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.

这题想法就是用两个pointer,一个比另外一个领先k个位置。对于上面那个例子,初始p1=1,p2=3;结束时p1=3,p2=5。

先扫描一遍链表,得到链表的长度,然后用k = n % length得到实际需要rotate的长度。

特殊情况:

1.list是空的

2.k=0

public class Solution {
    public ListNode rotateRight(ListNode head, int n) {
        if(head == null)
            return null;
        //get the length of the list
        ListNode p1 = head;
        int length = 1;
        while(p1.next != null){
            length++;
            p1 = p1.next;
        }
        //get the rounded amount to rotate
        int k = n % length;
        //if k is zero, return as is
        if(k == 0)
            return head;
        //use two pointers with k distance
        p1 = head;
        ListNode p2 = head;
        for(int i = 0; i < k; i++){
            p2 = p2.next;
        }
        while(p2.next != null){
            p1 = p1.next;
            p2 = p2.next;
        }
//the new head pointer is p1.next
        p2 = head;
        ListNode newHead = p1.next;
        p1.next = null;
        ListNode p3 = newHead;
        while(p3.next != null){
            p3 = p3.next;
        }
        p3.next = p2;
        
        return newHead;
    }
}


可以优化一下:

第一遍跑到尾巴得到长度以后,直接p2.next = head,把尾巴和头连起来,然后再跑length - k长度,把next设置成null即可。这样少了一次扫描,也不用考虑k=0的情况了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值