Topic: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.
Solution: In the initial state, let the pointer p point to the first node, Q points to the second node, when Q is not empty, exchange the value of the two node, then p points to the node behind Q, Q points to the node after P, Exchange node value, a loop pipe until an empty node is encountered. The code is as follows:
struct Listnode{int val; ListNode *next; ListNode (int x): Val (x), Next (NULL) {}}; ListNode *swappairs (ListNode *head) {if (head = = NULL | | head->next = NULL) return head; ListNode *p = head; ListNode *q = p->next;while (q) {int temp;temp = P->val;p->val = Q->val;q->val = Temp;if (q->next! = NULL ) {p = q->next;if (P->next! = NULL) q = p->next;elsebreak;} Elsebreak;} return head;}
"Leetcode OJ" Swap Nodes in Pairs