Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hi, the problem I\'m facing is I given a circular linked list, I need to swap th

ID: 3793382 • Letter: H

Question

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.

Explanation / Answer

//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;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote