Leetcode 24. Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list’s nodes (i.e., only nodes themselves may be changed).
1 -> 2 -> 3 -> 4
2 -> 1 -> 4 -> 3
nullptr
if the head of the list is nullptr
.To solve this problem, we will:
#include <iostream>
// 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) {
ListNode dummy(0);
dummy.next = head;
ListNode* current = &dummy;
while (current->next != nullptr && current->next->next != nullptr) {
ListNode* first = current->next;
ListNode* second = current->next->next;
// Swapping the nodes
first->next = second->next;
second->next = first;
current->next = second;
// Move to the next pair
current = first;
}
return dummy.next;
}
};
// Helper function to print the linked list
void printList(ListNode* node) {
while (node != nullptr) {
std::cout << node->val << " -> ";
node = node->next;
}
std::cout << "nullptr" << std::endl;
}
// Main function for testing purposes
int main() {
Solution solution;
// Creating a sample linked list 1 -> 2 -> 3 -> 4
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
// Print the original list
std::cout << "Original list: ";
printList(head);
// Swapping nodes in pairs
ListNode* newHead = solution.swapPairs(head);
// Print the modified list
std::cout << "Swapped list: ";
printList(newHead);
return 0;
}
The time complexity of this algorithm is (O(n)), where (n) is the number of nodes in the linked list. This is because we traverse the list in a single pass, swapping pairs of nodes as we go.
The space complexity is (O(1)) because we only use a few additional pointers, and we are not using any additional data structures that grow with the input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?