Problem Description: Give a sequence, swap each adjacent two elements, and return the head node. For example: 1-2-3-4 return sequence 2-1-4-3
Algorithm idea: In addition to the first set of elements, each other to exchange a pair of elements, to change four pointers. So, define four pointers. Only two of these pointers are not wanted off, others depend on these two pointers.
Public StaticListNode Swappairs (ListNode head) {ListNode Pprepre=NULL;//former elements of a node pairListNode Ppre =NULL;//The previous element of a node pair, dependent on pListNode p = head;//The first element of a pair of nodes to moveListNode Pnext =NULL;//the second element of a pair of nodes, dependent on p while(P! =NULL&& P.next! =NULL) {Ppre=p; P=P.next; Pnext=P.next; if(Ppre = =head) {Head=p; } if(Pprepre! =NULL) {Pprepre.next=p; } P.next=Ppre; Ppre.next=Pnext; Pprepre= Ppre;//all other elements depend on p, but Pprepre does not depend on p, so each move Pprepre and Pp =Pnext; } returnHead; }
Swap Nodes in Pairs, paired pairs of elements