2023.9.5
先将链表中的节点存储到数组中,再利用双指针重新构造符合条件的链表。代码如下:
/**
* 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<ListNode*> 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;
}
};