定义快慢指针令其分别等于p,q,找到倒数两个节点r,s,将最后一个节点s按规则插入到相应位置,将r->next=nullptr,接着将之前定义的p,q指针依次向后移动,重复之前操作,完成。
class Solution {
public:
void reorderList(ListNode *head) {
if (head == NULL || head->next==NULL || head->next->next ==NULL) return ;
ListNode* p=head;ListNode* r=head;
ListNode* q=head->next;ListNode* s=head->next;
while(q->next!=NULL)
{
while(s->next!=NULL)
{r=r->next;s=s->next;}
p->next=s;s->next=q;r->next=NULL;
if (q->next!=NULL){p=q;q=q->next;r=p;s=q;}
else break;
}
return;
}
};
京公网安备 11010502036488号