24. Swap Nodes in Pairs

1. Description

Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list’s nodes. Only nodes itself may be changed.

2. Example

Example 1:
Input: head = [1,2,3,4]
Output: [2,1,4,3]

Example 2:
Input: head = []
Output: []

Example 3:
Input: head = [1]
Output: [1]

3. Constraints

  • The number of nodes in the list is in the range [0, 100].
  • 0 <= Node.val <= 100

4. Solutions

My Accepted Solution

n is the sum of nodes in m_head
Time complexity: O(n)
Space complexity: O(1)

class Solution 
{
public:
    // ListNode* swapPairs(ListNode* head)
    ListNode* swapPairs(ListNode *m_head) 
    {
        if(!m_head || !m_head->next) return m_head;
        
        auto result = new ListNode();
        result->next = m_head;
        for(auto iter = result, firstNode = m_head, secondNode = m_head->next; firstNode && firstNode->next; )
        {
            firstNode->next = secondNode->next;
            secondNode->next = firstNode;
            iter->next = secondNode;
            
            iter = firstNode;
            firstNode = firstNode->next;
            secondNode = (firstNode ? firstNode->next : nullptr);
        }
        
        return result->next;
    }
};
comments powered by Disqus