Idea: El método utilizado por los individuos es relativamente común. Utilizando las características de las pilas y referencias, déjelas retroceder una por una y luego conectarlas; otra idea breve es usar el puntero de velocidad para encontrar el punto medio y dividir la lista vinculada original en dos Lista vinculada, luego invierta el orden de la lista vinculada hacia atrás y luego inserte la lista vinculada hacia atrás en la lista vinculada al frente;
void fun(ListNode *&head1, ListNode *head2, int &size, int now, bool &flag)
{
if (head2 == nullptr) //到达链表尾节点
{
return;
}
size += 1;//size用于统计链表元素个数
fun(head1, head2->next, size, now + 1, flag);
if (flag) //链表重排已完成,只需要一直return回去即可
{
return;
}
if ((now - 1 == size / 2 && !(size & 1)) || head1 == head2)//如果排到了重点
{
head2->next = nullptr;
flag = true;
}
else
{
ListNode *temp = head1->next;
head1->next = head2;
head2->next = temp;
head1 = temp;
}
}
void reorderList(ListNode *head)
{
//栈+引用递归下去
ListNode *head1 = head, *head2 = head;
int size = 0;
bool flag = false;
fun(head1, head2, size, 1, flag);
}