-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path24. Swap Nodes in Pairs
30 lines (26 loc) · 1.01 KB
/
24. Swap Nodes in Pairs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==NULL) return NULL; // for input like [] or the last condition when node will not exist
ListNode* temp=head;
if(head->next){
ListNode* other=head->next->next; //it will point to null if it does not exist and the first if codition will take care of null nodes
head=head->next;
head->next=temp;
temp->next= swapPairs(other);
}
return head;
}
};
/*Runtime: 0 ms, faster than 100.00% of C++ online submissions for Swap Nodes in Pairs.
Memory Usage: 7.5 MB, less than 92.21% of C++ online submissions for Swap Nodes in Pairs.*/