2019 重排链表

思想:采用两个指针交替进行,找到中间节点;将单链表的后半段节点原地逆置;将单链表前后两段中依次各取一个节点,按要求重排;

代码:

void change_list(Node *h)
{
    Node *p,*q,*r,*s;
    p=q=h;
    while(q->next!=NULL)
    {
        p=p->next;//p走一步
        q=q->next;
        if(q->next!=NUll)q=q->next;//q走两步
    }
    q=p->next//p指向为中间节点,q为后半段链表首节点
    p->next=NULL//断开链表
    while(q!=NULL)//将后半段逆置
    {
        r=q->next;
        q->next=p->next;
        p->next=q;
        q=r;
    }
    s=h->next;//s指向插入点
    q=p->next;
    p->next=NULL;
    while(q!=NULL)
    {
        r=q->next;
        q->next=s->next;
        s->next=q;
        q=r;
        
    }
    
}

猜你喜欢

转载自www.cnblogs.com/yangmenda/p/11708014.html