leetcode 143. 重排链表

2023.9.5

leetcode 143. 重排链表_第1张图片

        先将链表中的节点存储到数组中,再利用双指针重新构造符合条件的链表。代码如下:

/**
 * 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) {
        vector v;
        ListNode* cur = head;
        while(cur)
        {
            v.push_back(cur);
            cur = cur->next;
        }
        cur = head;
        int left = 1;
        int right = v.size()-1;
        int num = 0;
        while(left <= right)
        {
            if(num % 2 == 0)
            {
                cur->next = v[right];
                cur = cur->next;
                num++;
                right--;
            }
            else
            {
                cur->next = v[left];
                cur = cur->next;
                num++;
                left++;
            }
        }
        cur->next = nullptr;
    }
};

 

你可能感兴趣的:(leetcode专栏,leetcode,链表,算法,数据结构,cpp)