Leetcode one question of the day: 143.reorder-list (reorder list)

Insert picture description here
Idea: The method used by individuals is relatively common. Using the characteristics of stacks and references, let them go back one by one, and then connect them; another brief idea is to use the speed pointer to find the midpoint and divide the original linked list into two Linked list, then reverse the order of the back linked list, and then insert the back linked list into the front linked list;
Insert picture description here

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);
}

Guess you like

Origin blog.csdn.net/wyll19980812/article/details/109187096