My code is like this:
classSolution { Public: ListNode*swappairs (ListNode *head) { Const intTRUE =1; Const intFALSE =0; ListNode*ListA; ListNode*Listb; ListNode*Listfront; ListNode*Listtail; BOOLBfirsttime =TRUE; Listfront=Head; while(Listfront! =NULL) {ListA=Listfront; if(bfirsttime) {Listtail=Listfront; } Listb= listfront->Next; if(!bfirsttime && Listb = =NULL) { returnHead; } if(Bfirsttime && listb==NULL) { returnListA; } Listfront= listfront->next->Next; if(Bfirsttime && Listb! =NULL) {Head=Listb; Bfirsttime=FALSE; } if(!bfirsttime) {Listtail->next =Listb; Listtail=ListA; } Listb->next =ListA; ListA->next =Listfront; } returnHead; }};
Online Search for the Great God Code:
classSolution { Public: ListNode*swappairs (ListNode *head) { //Start Typing your/C + + solution below//Do not write int main () functionListNode *cur = null, *next = NULL, *tmp = NULL, *pre =NULL; Cur=Head; if(cur! = NULL && Cur->next! =NULL) Head= cur->Next; while(cur! =NULL) { if(Cur->next = =NULL) { returnHead; } Next= cur->Next; if(Pre! =NULL) Pre->next =Next; TMP= next->Next; Next->next =cur; Cur->next =tmp; Pre=cur; Cur= cur->Next; } returnHead; }};
The main consideration of this problem is the storage of the pointer information of the subsequent nodes when the two nodes are exchanged. A->b->c->d, after a transformation b->a->c->d->e, you cannot lose the pointer to a ptail, because the marker pointer has moved to the next processing unit after a transform, that is, the PA points to the C,PB point D, Pfront points to E, the second exchange if no ptail changes become b->a->c<-d, the list loses the D element and the interchange fails. So the next step in the second exchange is to just want the pointer of a ptail->next = Pb;ptial = PA; Complete the right first connection. The above is a major exchange of ideas.
Also considered is the end of the program flag, considering that there is only one input, and several input when the value of the Ptr->next is NULL, my program added a bfirst make it complicated to consider the situation, the code to observe others, directly using if (curr!=null && cur->next!=null) to identify as the head node, where it does not execute when there is only one node. And inside the loop, use if (Curr->next = = NULL) to return head as the end sign; The structure of the program is clear. Where the exchange of Ptail is described earlier.
Summary: The end condition of the program, the initial conditions must be clear and simple.
Leetcode 2:swap Nodes in Pairs