leetcode 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.
题目意思就是往右将list移动k个位置,这里需要注意的是k可能大于list的长度,因此首先求取list的长度是需要的。
本题最主要设置2个指针,位置相差k。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null){
            return head;
        }
        ListNode pre = head;
        int length = 0;
        while(pre != null){
            pre = pre.next;
            length++;
        }
        k = k % length;
        pre = head;
        ListNode tal = head;
        for(int j = 0; j < k; j++){
            tal = tal.next;
        }
        while(tal.next != null){
            tal = tal.next;
            pre = pre.next;
        }
        tal.next = head;
        head = pre.next;
        pre.next = null;
        return head;
    }
}
这里出现冗余的地方是两个指针的位置,可以看到,最后tal指针停下来的位置是list的最后一个节点,与求长度时pre指针的停下的位置相同,
因此tal指针不需要额外再使用循环了,只需要找到pre的位置即可。
<pre name="code" class="java">/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null){
            return head;
        }
        ListNode pre = head;
        ListNode tal = head;
        int length = 1;
        while(tal.next != null){
            tal = tal.next;
            length++;
        }
        k = k % length;
        for(int i = 0; i < length - k - 1; i++){
            pre = pre.next;
        }
        tal.next = head;
        head = pre.next;
        pre.next = null;
        return head;
    }
}
 

虽然减少了一个for循环,但从测试结果来看,时间上差不多,都是1ms,但这样思路也更清晰了些。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值