1. 程式人生 > >61 旋轉連結串列

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;
    }