FTPrep, 61 Rotate List

这道题,就相当于拿到找倒数第k个node的那道题,只不是改了一下题面。倒数题的链接:点击打开链接

多出的部分就是:1,要知道总长,k如果大于len,其实是要找到k%len 倒数的位置。

2,最后记得要把 curr.next 变成 null,否则就是个环状list,最后输出结果时会 把内存爆了。

顺便说一下:如果这道题是array的输出,实现时间 O(N),实现空间O(1)


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */

/*
public class ListNode{
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}
*/

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head==null || k==0) return head;
        ListNode dummy= new ListNode(-1);
        dummy.next = head;
        int len=0;
        ListNode curr = dummy;
        while(curr.next!=null){
            len++;
            curr=curr.next;
        }
        int moves= k%len;
        curr=dummy;
        ListNode end = dummy;
        for(int i=0; i<moves; i++){
            end=end.next;
        }
        while(end.next!=null){
            curr=curr.next;
            end=end.next;
        }
        end.next=dummy.next;
        dummy.next=curr.next;
        curr.next=null;
        return dummy.next;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值