1. Array Value Swapping (Naive Value Modification)
Intuition
1. Collect node values into a vector/list.
2. Iterate through indices i = 0, 2, 4, ... < len - 1 and swap vals[i] with vals[i + 1].
3. Traverse linked list and overwrite node values with the swapped array.
When to apply: Quick conceptual demonstration (note: many interviewers forbid value swapping and require node pointer mutation).
Algorithm
- Traverse linked list and append values to array.
- Swap values in adjacent pairs in array.
- Write swapped values back into linked list nodes.
#include <iostream>#include <vector>#include <algorithm> 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 || !head->next) return head; std::vector<int> vals; ListNode* curr = head; while (curr != nullptr) { vals.push_back(curr->val); curr = curr->next; } for (size_t i = 0; i + 1 < vals.size(); i += 2) { std::swap(vals[i], vals[i + 1]); } curr = head; for (int v : vals) { curr->val = v; curr = curr->next; } return head; }}; int main() { ListNode* head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4)))); Solution sol; ListNode* res = sol.swapPairs(head); while (res != nullptr) { std::cout << res->val << " "; res = res->next; } std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— Extracting, swapping in array, and rewriting values each take O(N) operations. - Space complexity:
O(N)— Requires O(N) auxiliary array space.