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.
Solution One: Recursion
/** 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 = = NULL | | head->next = =NULL)returnHead; ListNode* Newhead = head->Next; Head->next = Swappairs (newhead->next); Newhead->next =Head; returnNewhead; }};
Solution Two: Reverse Nodes in K-group order k=2
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode*swappairs (ListNode *head) { returnReversekgroup (Head,2); } ListNode*reversekgroup (ListNode *head,intk) {ListNode* Newhead =NewListNode (-1); ListNode* Tail =Newhead; ListNode* begin =Head; ListNode* end =begin; while(true) { intCount =K; while(Count && End! =NULL) {End= end->Next; Count--; } if(Count = =0) {//reverse from [begin, end]Stack<listnode*>s; while(Begin! =end) {S.push (begin); Begin= begin->Next; } while(!S.empty ()) {ListNode* top =S.top (); S.pop (); Tail->next =top; Tail= tail->Next; } } Else {//Leave outTail->next =begin; Break; } } returnNewhead->Next; }};
Solution Three:
After each pair of nodes 22 is exchanged, a connection is returned to the previous node.
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode*swappairs (ListNode *head) {ListNode* Newhead =NewListNode (-1); Newhead->next =Head; ListNode* cur =Newhead; while(Cur->next! = NULL && Cur->next->next! =NULL) {cur->next = Reverse (Cur->next, cur->next->next); Cur= cur->next->Next; } returnNewhead->Next; } ListNode* Reverse (listnode* N1, listnode*n2) {//swap adjacent nodes, the latter is returnedN1->next = n2->Next; N2->next =N1; returnN2; }};
"Leetcode" Swap Nodes in Pairs (3 solutions)