143. 重排链表

  1. 重排链表
    给定一个单链表 L 的头节点 head ,单链表 L 表示为:

L0 → L1 → … → Ln - 1 → Ln
请将其重新排列后变为:

L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例 1:

输入:head = [1,2,3,4]
输出:[1,4,2,3]
示例 2:

输入:head = [1,2,3,4,5]
输出:[1,5,2,4,3]

/**
 * 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:
    int getLen(ListNode *head) {
        ListNode *temp = head;
        int len = 0;
        while(temp) {
            len++;
            temp = temp->next;
        }
        return len;
    }
    void reorderList(ListNode* head) {
        vector<ListNode *> vecLeftNode, vecRightNode;
        int len = getLen(head);
        int left = 0, right = 0;
        if(len % 2 == 1) {
            left = len / 2 + 1;
            right = len / 2;
        } else {
            left = len / 2;
            right = len / 2;
        }
        int leftIndex = 0, rightIndex = 0;
        ListNode *temp = head;

        while(leftIndex < left) {
            vecLeftNode.push_back(temp);
            temp = temp->next;
            leftIndex++;
        }
        while(leftIndex < left) {
            vecLeftNode.push_back(temp);
            temp = temp->next;
            leftIndex++;
        }
        
        while(rightIndex < right) {
            vecRightNode.push_back(temp);
            temp = temp->next;
            rightIndex++;
        }

        ListNode *newHead = new ListNode(0);
        reverse(vecRightNode.begin(), vecRightNode.end());
        ListNode *tempH = newHead;
        leftIndex = 0, rightIndex = 0;
        while(leftIndex < left && rightIndex < right) {
            tempH->next = vecLeftNode[leftIndex++];
            tempH = tempH->next;
            tempH->next = vecRightNode[rightIndex++];
            tempH = tempH->next;
        }
        while(leftIndex < left) {
            tempH->next = vecLeftNode[leftIndex++];
            tempH = tempH->next;
        }
        tempH->next = nullptr;
        head = newHead->next;
        delete(newHead);
    }
};

标准答案:

你可能感兴趣的:(leetcode算法刷题记录,链表,数据结构)