给定一个单链表 L 的头节点 head ,单链表 L 表示为:
L0 → L1 → … → Ln - 1 → Ln
请将其重新排列后变为:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
![img](https://i-blog.csdnimg.cn/blog_migrate/597f7fd619eae90993fac93f4127f331.png)
输入:head = [1,2,3,4]
输出:[1,4,2,3]
![img](https://i-blog.csdnimg.cn/blog_migrate/9951deb93aba9c7593fe96719b72b6b4.png)
输入:head = [1,2,3,4,5]
输出:[1,5,2,4,3]
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/f7884375d70167fdb838124f15b9c6eb.jpeg#pic_center)
class Solution{
public:
void reorderList(ListNode* head){
vector<ListNode*> vec;
ListNode* cur = head;
if(cur == nulptr)
return;
while(cur != nullptr){
vec.push_back(cur);
cur = cur->next;
}
cur = head;
int i = 1;
int j = vec.size()-1;
int count = 0;
while(i<=j){
if(count%2 == 0){
cur->next = vec[j];
j--;
}
else{
cur->next = vec[i];
i++
}
cur = cur->next;
count++;
}
cur->next = nullptr;
}
};