LeetCode 24. Swap Nodes in Pairs
Linked List
Input: head = [1,2,3,4]
Output: [2,1,4,3]Input: head = []
Output: []Input: head = [1]
Output: [1]Solution:
Last updated
Linked List
Input: head = [1,2,3,4]
Output: [2,1,4,3]Input: head = []
Output: []Input: head = [1]
Output: [1]Last updated
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
ListNode* new_head = head->next;
head->next = swapPairs(new_head->next);
new_head->next = head;
return new_head;
}
};