Given a linked list, swap every, adjacent nodes and return its head.
For example,
Given 1->2->3->4 , you should return the list as 2->1->4->3 .
Your algorithm should use only constant space. Modify the values in the list, only nodes itself can be changed.
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * struct ListNode *next;6 * };7 */8 structlistnode* Swappairs (structlistnode*head)9 {Ten structListNode *p=head,*q=head; One A intlisklen=0; - - while(q!=NULL) the { -lisklen++; -Q=q->Next; - } + if(lisklen%2==0) - { + while(p!=NULL) A { at inttemp; -Temp=p->Val; -P->val=p->next->Val; -P->next->val=temp; - -P=p->next->Next; in } - } to Else + { - while(p->next!=NULL) the { * inttemp; $Temp=p->Val;Panax NotoginsengP->val=p->next->Val; -P->next->val=temp; the +P=p->next->Next; A } the } + - returnhead; $}
Leecode-swap Nodes in Pairs