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

JAVA: Linked list problem I have a node class say: *****************************

ID: 3864857 • Letter: J

Question

JAVA: Linked list problem

I have a node class say:

************************************************

   private static class Node {

       private int data;

private Node right;

       private Node down;

       public Node(Node down, int data, Node right) {

           this.down = down;

           this.data = data;

           this.right = right;

}

   }

****************************************************************

I need to make a grid class whose constructor needs to links the rows and columns of the Nodes of for example a 5x4 grid.

so

public class Grid{

private Node head;

public Grid(){

//at (0,0), it would connect to all the nodes below it and all the nodes to the right of it. and so on and so on

//I'd also note it should be a circularly linked list.

}

}

anyhelp settting up that constructor would be appreciated. Lmk if you need more info

Explanation / Answer

package Stack;

public class Grid {
   GridNode head;
   public Grid(int row,int col){
       head = new GridNode(null, 0, null);
       GridNode temp = head;
       for(int i=0;i<row-1;i++){
           temp.setDown(new GridNode(null, i, null));
           temp = temp.getDown();
           System.out.println("i "+i);
       }
       for(int i=0;i<col-1;i++){
           temp.setRight(new GridNode(null, i, null));
           temp = temp.getRight();
           System.out.println("i "+i);
       }
      
       GridNode node = head;
       for(int i=0; i<col-1; i++){
           GridNode colNode = node;
           for(int j=0; j<row-1; j++){
               GridNode newNode = new GridNode(null, i+1, null);
               GridNode right = colNode.getRight();
               if(right != null){
                   right.setDown(newNode);
               }
               GridNode down = colNode.getDown();
               if(down != null){
                   down.setRight(newNode);
               }
              
           }
           node = node.getDown();
       }
   }
}


//==================================================//

package Stack;

public class GridNode {
   private int data;
   private GridNode right;
   private GridNode down;
   public GridNode(GridNode down, int data, GridNode right) {
       this.setDown(down);
       this.setData(data);
       this.setRight(right);
   }
   public int getData() {
       return data;
   }
   public void setData(int data) {
       this.data = data;
   }
   public GridNode getRight() {
       return right;
   }
   public void setRight(GridNode right) {
       this.right = right;
   }
   public GridNode getDown() {
       return down;
   }
   public void setDown(GridNode down) {
       this.down = down;
   }
}