水下功夫做透,水上才能顺风顺水。

旋转链表

 public ListNode rotateRight(ListNode head, int k) {
        if(head==null||head.next==null||k==0){
            return head;
        }
        ListNode slow = head;
        ListNode fast = head;
        int len = calculateLen(head);
        k = k%len;
        while(k>0){
            fast = fast.next;
            k--;
        }
        while(fast.next!=null){
            fast = fast.next;
            slow = slow.next;
        }
        fast.next = head;
        head = slow.next;
        slow.next = null;
        return head;
    }

    private int calculateLen(ListNode head){
        int len = 0;
        while (head!=null) {
            head = head.next;
            len++;
        }
        return len;
    }

 

posted @ 2022-03-05 21:00  北方寒士  阅读(17)  评论(0编辑  收藏  举报