题目:
题解:
- 暴力法,将链表节点全部存入数组中,然后每次取首尾元素进行相连就好了。
代码如下:
class Solution {
public:
//题目意思:每次头尾头尾头尾取元素,组成新的链表
//题解:暴力法,将链表的节点存放在一个数组中,然后每次取首尾元素进行相连就好了
void reorderList(ListNode* head) {
if(!head)return;
vector<ListNode*> record;
while(head){
record.push_back(head);
head=head->next;
}
int left=0,right=record.size()-1;
while(left<right){
//首尾组合连接
record[left]->next=record[right];
++left;
if(left==right)break;//表示有偶数个节点,重排后相遇了,需要退出
//尾节点需要连接下次首尾组合的首节点
record[right]->next=record[left];
right--;
}
//置尾后节点为空
record[left]->next=nullptr;
}
};