Hi the problem Im facing is I given a circular linked list I
Hi, the problem I\'m facing is I given a circular linked list, I need to swap the rear of the list with the front of the list, then swap the front.next (or just the one before that).
So for example, given numbers:
1 4 2 5 6 7 3
Swap
3 4 2 5 6 7 1
Swap again
4 3 2 5 6 7 1
My code for this problem is:
CardNode ptr = deckRear.next;
CardNode prev = deckRear;
do {
ptr = ptr.next;
prev = prev.next;
if (ptr.cardValue == 27) {
prev.next = ptr.next;
ptr.next = ptr.next.next;
prev.next.next = ptr;
}
} while (ptr != deckRear.next);
This works when the number is next to eachother, but NOT when the number is the rear or 2nd to the rear. Any help is appreciated, thank you.
Solution
//you have not, specifed that you need only two swaps or entire list (specifically..)..
//for the example given above this code might work..
CardNode ptr = deckRear.next;
CardNode temp=ptr;
CardNode prev = deckRear;
while(ptr.next!=prev)
{
ptr = ptr.next;
}
if(temp==ptr)
{
ptr=prev;
}
else
{
CardNode temp1=temp.next;
prev.next=temp1.next;
temp1.next = prev;
ptr.next = temp;
temp =temp1;
}

