61 旋转链表

61 旋转链表

一般解法

    ListNode *rotateRight(ListNode *head, int k) {
        if (head == nullptr || head->next == nullptr || k == 0)
            return head;
        int len = 0;
        ListNode *pre = head;
        while (pre) {
            pre = pre->next;
            ++len;
        }
        int num = k % len;
        if (num == 0)
            return head;
        ListNode prehead(-1);
        prehead.next = head;
        ListNode *back = &prehead;
        pre = &prehead;
        for (int pos = len - num; pos > 0; --pos, pre = pre->next);
        while (pre->next) {
            ListNode *temp = pre->next;
            pre->next = pre->next->next;
            temp->next = back->next;
            back->next = temp;
            back = back->next;
        }
        return prehead.next;
    }

好一点解法

    ListNode *rotateRight(ListNode *head, int k) {
        if (head == nullptr || head->next == nullptr || k == 0)
            return head;
        int len = 0;
        ListNode *pre = head;
        while (pre) {
            pre = pre->next;
            ++len;
        }
        int num = k % len;
        if (num == 0)
            return head;
        ListNode prehead(-1);
        prehead.next = head;
        ListNode *back = &prehead;
        pre = back;
        for (int pos = len - num; pos > 0; --pos, pre = pre->next);
        for (back = pre; back->next != nullptr; back = back->next);
        back->next = prehead.next;
        prehead.next = pre->next;
        pre->next = nullptr;
        return prehead.next;
    }
原文地址:https://www.cnblogs.com/INnoVationv2/p/10175987.html