FTPrep, 61 Rotate List

来源:互联网 发布:网络模式怎么设置 编辑:程序博客网 时间:2024/06/13 11:34

这道题,就相当于拿到找倒数第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;    }}


原创粉丝点击