24. Swap Nodes in Pairs
Medium
100890FavoriteShare
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
Runtime: 4 ms, faster than 100.00% of C++ online submissions for Swap Nodes in Pairs.
Memory Usage: 8.8 MB, less than 79.81% of C++ online submissions for Swap Nodes in Pairs.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void swap(ListNode* A, ListNode* B)
{
if(A==NULL||B==NULL)return;
ListNode* dummy=new ListNode(0);
dummy->next=B->next;
B->next=A;
if(dummy->next==NULL)
{
A->next=NULL;return;
}
if(dummy->next->next==NULL)
{
A->next=dummy->next;return;
}
A->next=dummy->next->next;
return swap(dummy->next,dummy->next->next);
}
ListNode* swapPairs(ListNode* head) {
if(head==NULL||head->next==NULL)return head;
ListNode* dummy=new ListNode(0);
dummy->next=head->next;
swap(head,head->next);
return dummy->next;
}
};