Idea 1:
classSolution { Public://Two pointers, p, Q, Q pointing to the second, Prep is p beforeListNode *swappairs (ListNode *head) { if(head = = NULL)returnNULL; Auto P=Head; Auto Q= head->Next; ListNode Prehead (-1); ListNode* PreP = &Prehead; PreP->next =p; ListNode*tmp; while(q) {PreP->next =Q; TMP= q->next;//after recording Q, as the next PQ->next =p; PreP=p; if(TMP) P =tmp; Else Break; Q= p->Next; } returnPrehead.next; }};
The result is timed out, later looked at the other answer after the discovery is tmp=q->next this sentence processing bad, should not use the temporary variable, but with p->next = q->next; so the next p can be p->next:
classSolution { Public://Two pointers, p, Q, Q pointing to the second, Prep is p beforeListNode *swappairs (ListNode *head) { if(head = = NULL)returnNULL; Auto P=Head; Auto Q= head->Next; ListNode Prehead (-1); ListNode* PreP = &Prehead; PreP->next =p; while(q) {PreP->next =Q; P->next = q->next;//after recording Q, as the next PQ->next =p; PreP=p; P= p->Next; Q= p?p->next:nullptr; } returnPrehead.next; }};
Leetcode--swap Nodes in Pairs