My c++/c solution with O(n) time and O(1) space


  • 0
    2

    My solution has three steps,each of steps complete a simple task.

    '''

    if(head==NULL || head->next==NULL || head->next->next==NULL)
    return;

    Node *slow,*fast;
    slow=fast=head;
    while(fast->next!=NULL && fast->next->next!=NULL)
    {
        fast=fast->next->next;
        slow=slow->next;
    }
    revers(slow);
    
    Node *q=slow->next,*p=head,*s=p->next;
    slow->next=NULL;
    while(q!=NULL)
    {
        p->next=q;
        p=q;
        q=s;
        s=p->next;
    }
    

    void revers(Node *head)
    {
    Node *p=head->next,*s=p;
    head->next=NULL;

    while(p!=NULL)
    {
        s=s->next;
        p->next=head->next;
        head->next=p;
        p=s;
    }
    

    }
    '''


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.