1

so using a singly-linked approach, I'm trying to create a two dimensional linked list(matrix). The matrix will be constructed with specified dimension(ex 3x4 matrix). Below is my code.

class MLink{
public MLink nextCol;
public MLink nextRow;
public long data;
//----------------------------------
MLink(long data){
    this.data = data;
    nextCol = null;
    nextRow = null;
}
//----------------------------------
public void displayLink(){
    System.out.print("{"+data+"} ");
}
//----------------------------------
}// end class MList

class MLinkList{
private MLink first;
private MLink current;
private int rows;
private int cols;
//----------------------------------
MLinkList(int rows, int cols){
    this.rows = rows;
    this.cols = cols;
    MLink newLink = new MLink(0);
    first = newLink;
    current = first;
    for(int i=0;i<rows;i++){
        current.nextRow = new MLink(0);
        for(int j=0;j<cols;j++){
            current.nextCol = new MLink(0);
        }
    }
}
//----------------------------------
public boolean isEmpty(){
    return (first==null);
}
//----------------------------------




}//end class MLinkList
public class MatrixListApp {

public static void main(String[] args) {
    MLinkList q = new MLinkList(3,4);

}

}

I have to admit that I haven't made much progress because I got stuck at initializing the matrix in the MLinkList constructor. What I wanna do is I want to fill up the matrix with MLinks with 0 and then work my way up from there. I assume that I would have to move my current along the matrix to fill the matrix but how can I do so?

Any help is appreciated.

2
  • Why are you using a linked list structure if you know the size of the matrix upfront? Commented Mar 1, 2016 at 12:20
  • 1
    Just to practice I guess. It's a problem from the book. I'm pretty sure array would be a better fit.. Commented Mar 1, 2016 at 12:22

1 Answer 1

2

You need two current values, the current row and the current cell in the current column.

To move alone the columns you would do currentCell = curretnCell.nextCol;

Sign up to request clarification or add additional context in comments.

2 Comments

thank you for the reply. I've made a bit of progress adopting your solution. But I seem to be making 5 cells(when I put 2x2) instead of 4. Can you point out the part that I messed up?
MLink currentCol; for(int i=0;i<rows;i++){ currentCol = current; for(int j=1;j<cols;j++){ currentCol.nextCol = new MLink(0); currentCol = currentCol.nextCol; } current.nextRow = new MLink(0); current = current.nextRow; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.