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.
Subscribe to see which companies asked this question
Code that is not optimized, with 3 temporary pointers
listnode* Swappairs (listnode*head) { if(head = = Nullptr | | head->next = =nullptr)returnHead; ListNode*pre =Head; ListNode*cur = pre->Next; ListNode*net = cur->Next; Head=cur; while(true) {cur->next =Pre; if(NET = = Nullptr | | net->next = =nullptr) {Pre->next =net; Break; } Pre->next = net->Next; Pre=net; Cur= pre->Next; NET= cur->Next; } returnhead;}
Amazing solution, with double pointers, open ideas, I think you can use the double pointer, it seems to be far worse
ListNode *swappairs (ListNode *head) { **p = &head; while (*p && (*p),next) { *t = (*p),next; (*p)->next = t->Next; T->next = *p; *p = t; = & (*p)->next->next; } return head;}
Swap Nodes in Pairs leetcode