Given a linked list of numbers. Swap every 2 adjacent links.

Posted by Learner on Stack Overflow See other posts from Stack Overflow or by Learner
Published on 2010-05-15T04:27:52Z Indexed on 2010/05/15 4:34 UTC
Read the original article Hit count: 164

Filed under:

Given a linked list of numbers. Swap every 2 adjacent links. For eg if a linked list given to you is- a->b->c->d->e->f O/p expected- b->a->d->c->f->e Every 2 alternate links have to be swapped.

I have written a solution here. Can you suggest me some other solution. Can you comment on my solution and help me better write it?

void SwapAdjacentNodes (Node head)
{
    if (head == null) return; 

    if (head.next == null) return; 
    Node curr = head;
    Node next = curr.Next;
    Node temp = next.Next;

    while (true)
    {
        temp = next.Next;
        next.Next = curr;
        curr.Next = temp;

        if  (curr.Next != null)
            curr = curr.Next;
        else
            break;
        if (curr.Next.Next!=null)
            next = curr.Next.Next;
        else
            break;
    }   
}

© Stack Overflow or respective owner

Related posts about interview-questions