24. Swap Nodes in Pairs
problem description
Given 1->2->3->4, you should return the list as 2->1->4->3.algorithm thought
code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==NULL||head->next==NULL)
return head;
ListNode*tmp=head->next;
head->next=swapPairs(tmp->next);
tmp->next=head;
return tmp;
}
};algorithm analysis
Last updated