<LinkedList> 61

61. Rotate List

方法一:做k次rotation。

1.corner case需要考虑

2.当k远远大于的计算量的时候,记得算出链表长度并对长度求余。

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null) return null;
        if(head.next == null) return head;
        int n = 0;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode cur = head;
        while(cur != null){
            n++;
            cur = cur.next;
        }
        k %= n;

        for(int i = 0; i < k; i++){
            ListNode pre = dummy;
            ListNode last = dummy.next;
            while(last.next != null){
                pre = pre.next;
                last = last.next;
            }
            last.next = dummy.next;
            dummy.next = last;
            pre.next = null;
        }
        return dummy.next;
    }
}

方法二:

原理是先遍历整个链表获得链表长度 i ,然后此时把链表头和尾链接起来,在往后走i - k % i个节点就到达新链表的头结点前一个点,这时把 Slow的下一个节点是头节点。

时间复杂度和空间复杂度都快很多。

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null || head.next == null) return head;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode fast = dummy, slow = dummy;
        
        int i;
        for(i = 0; fast.next != null; i++){
            fast = fast.next;
        }
        
        for(int j = i - k % i; j> 0; j--){
            slow = slow.next;
        }
        fast.next = dummy.next;
        dummy.next = slow.next;
        slow.next = null;
        return dummy.next;
    }
}
posted @ 2020-01-14 09:26  阿飞哦  阅读(323)  评论(0编辑  收藏  举报