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.
Idea: Split the list and then merge
List *swappairs (list *head) { if (head = = NULL | | head->next = = NULL) return head; list* Ji=head; list* OU = head->next; list* TEMP1,*TEMP2; list* l1= head; list* L2 = head->next; Temp1 = l2->next; while (Temp1! = NULL) { Temp2 = temp1->next; L1->next = Temp1; L2->next = Temp2; L1 = Temp1; L2 = Temp2; if (L2!=null) Temp1 = l2->next; else temp1 = NULL; } if (L1! = NULL) l1->next =null; if (L2! = null) l2->next = null; Temp1 = ou; while (Temp1! = null&&temp1->next! = NULL) { Temp2 = ji->next; Ji->next = temp1->next; Temp1->next = Ji; Temp1 = ji->next; Ji = temp2; } Temp1->next = Ji;
Swap Nodes in Pairs--leetcode