LeetCode(61)——Rotate List

题目:

Given a list, rotate the list to the right by k places, where k is non-negative.


Example:

Given 1->2->3->4->5->NULL and k = 2,

return 4->5->1->2->3->NULL.

AC:

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if (null == head || null == head.next) {
            return head;
        }
        
        ListNode dummyNode = new ListNode(-1);
        ListNode fastNode = dummyNode;
        ListNode endNode = null;
        dummyNode.next = head;
        int len = 0;
        while (null != fastNode.next) {
            fastNode = fastNode.next;
            len++;
        }
        endNode = fastNode;
        
        k = k % len;
        if (0 == k) {
            return head;
        }
        
        k = len - k;
        fastNode = dummyNode;
        while (k > 0) {
            fastNode = fastNode.next;
            k--;
        }
        
        dummyNode.next = fastNode.next;
        endNode.next = head;
        fastNode.next = null;
        
        return dummyNode.next;
    }
}
注意 k可能会大于链表长度,因此要对长度取余。

猜你喜欢

转载自blog.csdn.net/weixin_39120845/article/details/79455331