重排链表-链表143-C++

算法思想:

线性表:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode* head) {
        if(head == nullptr) return;
        
        vector<ListNode*> vec;
        ListNode* node = head;
        while(node != nullptr){
            vec.push_back(node);
            node = node->next;
        }
        
        int i = 0;
        int j = vec.size() - 1;
        while(i < j){
            vec[i]->next = vec[j];
            i++;
            
            if(i == j) break;
            
            vec[j]->next = vec[i];
            j--;
        }
        vec[i]->next = nullptr;
    }
};

重排链表-链表143-C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode* head) {
        if(head == nullptr) return;

        ListNode* mid = middle(head);
        ListNode* node = reverse(mid->next);
        mid->next = nullptr;
        merge(head, node);

    }

    ListNode* middle(ListNode* & head){
        if(head == nullptr) return nullptr;
        
        ListNode* slow = head;
        ListNode* fast = head;
        while(fast != nullptr && fast->next != nullptr){
            fast = fast->next->next;
            slow = slow->next;
        }

        return slow;
    }

    ListNode* reverse(ListNode* head){
        if(head == nullptr) return head;

        ListNode* pre = nullptr;
        ListNode* curr = head;
        ListNode* temp = curr;

        while(curr != nullptr){
            curr = curr->next;
            temp->next = pre;
            pre = temp;
            temp = curr;
        }
        return pre;
    }

    void merge(ListNode* & l1, ListNode* & l2){
        ListNode* l1_tmp = l1;
        ListNode* l2_tmp = l2;

        while(l1 != nullptr && l2 != nullptr){
            l1_tmp = l1->next;
            l2_tmp = l2->next;
            l1->next = l2;
            l2->next = l1_tmp;
            l1 = l1_tmp;
            l2 = l2_tmp;
        }
    }

};

上一篇:【143期】你知道 Java 是如何实现线程间通信的吗?


下一篇:C++描述 104.仓库选址