I don't know where is wrong


  • 0
    K

    when input is [1,2] , this will be TLE.

    struct ListNode* swapPairs(struct ListNode* head) {

    struct ListNode* newhead = malloc(sizeof(struct ListNode));
    struct ListNode* tmp;
    struct ListNode* a;
    a = newhead;
    while(head !=NULL && head->next!=NULL)   
    {
        tmp= head->next->next;
        newhead->next = head->next;
        newhead->next->next = head;
        head=tmp;
        newhead = newhead->next->next;
    }
    if(head !=NULL)
        newhead->next = head;
    return a->next;
    

    }


  • 0
    T

    That's because the linked list becomes a loop. You need to make head->next point to tmp before head points to tmp.


  • 0
    Y

    Hi guys, I encountered the same problem. I have looked at @triple's suggestion, but I couldn't understand. Could any of you explain more? or show me how to solve the cycle? Thanks.


  • 0

    @triple was right, after that becomes [2,1]. Since [1] still points to [2], which means [1]->next is equal to [2]. I think the test needs to move on to the next ListNode, but for your code this will never succeed because [1]->next is always [2] so you got the TLE.


  • 0

    @yizhu59 you have to make the final ListNode points to NULL instead of other ListNode.


Log in to reply
 

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