Skip to content

Latest commit

 

History

History
34 lines (26 loc) · 578 Bytes

5_pairwise_swap_element.md

File metadata and controls

34 lines (26 loc) · 578 Bytes

Pairwise swap elements of a linked list by changing links (non-recursive)

Code

Node *pairWiseSwap(Node *head)
{
    if (head == NULL || head->next == NULL)
        return head;

    Node *prev = head;
    Node *curr = head->next;

    head = curr;

    while (true)
    {
        Node *next = curr->next;
        curr->next = prev;

        if (next == NULL || next->next == NULL)
        {
            prev->next = next;
            break;
        }

        prev->next = next->next;

        prev = next;
        curr = prev->next;
    }
    return head;
}