LeetCode | Rotate List

https://leetcode.com/problems/rotate-list/

其实就是对链表进行循环移位。比如1->2->3->4->5->null,往右循环移2位,就是4->5->1->2->3->null

循环右移k位的思路是:

  1. 首先计算链表的长度len
  2. k = k mod len。因为k可能比链表长度还大,取余并不影响结果。
  3. 找到链表倒数第k+1个节点x,它将是新链表的末节点。(快慢指针)
  4. 以x为分界点,重新组合链表。
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if (!head || !head->next) return head;
        
        ListNode dummy(0); dummy.next = head;
        
        // get the length of the list
        int len = 1; ListNode *tail = head;
        while (tail->next) {
            len++;
            tail = tail->next;
        }
        k %= len;
        if (k == 0) return head;
        
        // find the (k+1)-th to the end of the list
        ListNode *prev = kth_to_end(&dummy, k + 1);
        
        // reconnect the list
        ListNode *new_head = prev->next;
        prev->next = NULL;
        tail->next = head;
        
        return new_head;
    }
    
    ListNode* kth_to_end(ListNode* head, int k) {
        ListNode *main_ptr = head, *ref_ptr = head;
        for (int i = 1; i < k; ++i) {
            ref_ptr = ref_ptr->next;
        }
        while (ref_ptr->next) {
            main_ptr = main_ptr->next;
            ref_ptr = ref_ptr->next;
        }
        return main_ptr;
    }
};
原文地址:https://www.cnblogs.com/ilovezyg/p/6384434.html