Fill in the method stub below to swap the second and third c

Fill in the method stub below to swap the second and third cells in the given linked list, and return a reference to the cell that ends up as the second cell of the list. Thus, for example, if the list contains the elements: 1, 2.5, 3.25, and 4.75, then the resulting list should contain the elements: 1, 3.25, 2.5, and 4.75, and a reference to the cell containing 3.25 should be returned. There may be additional references to some of the cells in the list; therefore, it is important to rearrange the actual cells, rather than copying the data from one cell to another. You may assume that the list contains at least three cells. You may not add any code outside of this method.

public LinkedListCell SwapSecondTwo(LinkedListCell list) {

Solution

Hi buddy, please find the below java program

import java.util.*;
import java.lang.*;
import java.io.*;

class LinkedListCell{
int n;
LinkedListCell next;
public LinkedListCell(int n){
this.n = n;
}
@Override
public String toString(){
return n+\"\";
}
}
class Main
{
  
public static LinkedListCell SwapSecondTwo(LinkedListCell list) {
//Storing first, second , third and fourth cells in the linked list
LinkedListCell first = list;
LinkedListCell second = first.next;
LinkedListCell third = second.next;
LinkedListCell fourth = third.next;
//Change the next element of the first to third;
first.next = third;
//Change the next element of the third to second;
third.next = second;
//Change the next element of the second to fourth
second.next = fourth;
//Returnt the reference to the second element
return first.next;
}
   public static void main (String[] args) throws java.lang.Exception
   {
       // your code goes here
       LinkedListCell a = new LinkedListCell(11);
       LinkedListCell b = new LinkedListCell(27);
       a.next = b;
       LinkedListCell c = new LinkedListCell(31);
       b.next = c;
       LinkedListCell d = new LinkedListCell(49);
       c.next = d;
       LinkedListCell ans = SwapSecondTwo(a);
       System.out.println(ans);
       System.out.println(\"first \"+a);
       System.out.println(\"second \"+a.next);
       System.out.println(\"third \"+a.next.next);
       System.out.println(\"fourth \"+a.next.next.next);
   }
}

OUTPUT :

31
first 11
second 31
third 27
fourth 49

Fill in the method stub below to swap the second and third cells in the given linked list, and return a reference to the cell that ends up as the second cell of
Fill in the method stub below to swap the second and third cells in the given linked list, and return a reference to the cell that ends up as the second cell of

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site