Given a linked list, swap every two 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. You may not 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 struct ListNode* swapPairs(struct ListNode* head) 9 { 10 struct ListNode *p=head,*q=head; 11 12 int LiskLen=0; 13 14 while(q!=NULL) 15 { 16 LiskLen++; 17 q=q->next; 18 } 19 if(LiskLen%2==0) 20 { 21 while(p!=NULL) 22 { 23 int temp; 24 temp=p->val; 25 p->val=p->next->val; 26 p->next->val=temp; 27 28 p=p->next->next; 29 } 30 } 31 else 32 { 33 while(p->next!=NULL) 34 { 35 int temp; 36 temp=p->val; 37 p->val=p->next->val; 38 p->next->val=temp; 39 40 p=p->next->next; 41 } 42 } 43 44 return head; 45 }