Swap Nodes in Pairs
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.
Analysis: A simpler list operation requires the conversion of a->b-> (B->next) to a form such as b->a-> (B->next)
Write your own code for
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* Swappairs (listnode*head) { if(Head ==nullptr | | head->next = =nullptr)returnHead; ListNode* cur =Head; ListNode* Curnext = cur->Next; Cur->next = curnext->Next; Curnext->next =cur; Head=Curnext; ListNode* prev =cur; while(Prev && prev->next) {cur= prev->Next; Curnext= cur->Next; if(curnext) {cur->next = curnext->Next; Curnext->next =cur; Prev->next =Curnext; Prev=cur; }Else{cur->next =Curnext; Prev=nullptr; } } returnHead; }};
Pointer-pointer solution presented in discuss, slightly more difficult, but very efficient
listnode* Swappairs (listnode* head) { **pp = &head, *a, *b; while ((a = *pp) && (b = a->next)) { a->next = b->Next; b->next = A; *PP = b; = & (A->next); } return head;}
Swap Nodes in Pairs