Given a linked list of numbers. Swap every 2 adjacent links. For example, if a linked list given to you is:
a->b->c->d->e->f
Output 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;
}
}
Take a look at this C++ solution:
public void exchangeAdjElements(){
LLMain backup=current.next;
LLMain temp = current.next;
LLMain previous=current;
while(current!=null && current.next!=null){
previous.next=current.next;
current.next=temp.next;
temp.next=current;
if(current.next!=null){
previous=current;
current=current.next;
temp=current.next;
}
}
current=backup;
}
Here current is the head node.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With