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

Use m singly linked lists to represent an m x n sparse matrix A, i.e. the values

ID: 3727078 • Letter: U

Question

Use m singly linked lists to represent an m x n sparse matrix A, i.e. the values in a small portion of cells are non-zero, where m and n can be quite large. Hence, array implementation will not be ACCEPTED. Write a program in Java to construct A. In this program, the input, i.e. m and n, should be inputted by a user. Moreover, the program needs to provide the following five functions:

1. Get the value at A(i, j) as given i and j;
2. Insert the value at A(i, j) as given i and j;
3. Delete the value at A(i, j) as given i and j;
4. Print the values at the j
th column of A as given j; 5. Print the values at the ith row of A as given i; where 1 i m and 1 j n.

Sample input and output:

Sparse Matrix setup No. of rows: 5
No. of columns: 4

5 x 4 sparse matrix is created.

> insert 10 3 2
Inserted 10 to cell(3,2).

> insert 20 2 3
Inserted 20 to cell(2,3).

> insert 30 1 1
Inserted 30 to cell(1,1).

> insert 40 2 2
Inserted 40 to cell(2,2).

> row 2
0 40 20 0

> col 2

0 40 10 0 0

> delete 2 3

delete cell(2,3).

> get 2 3
The value of cell(2,3) is 0.

> get 3 2
The value of cell(3,2) is 10.

> stop
Thank you for using this program!

Please don't just copy the answer from the question that I asked.

getRow() and getCol() are needed.

Explanation / Answer

import java.util.LinkedList;

import java.util.Scanner;

public class ArrayOfLinkedList {

public static LinkedList<Integer>[] linkedList;

public static int M,N;

public static void insertAt(int value,int i, int j){

linkedList[i-1].add(j-1,value );

System.out.println("Inserted "+value +" at ("+i+","+j+")");

}

public static int getValueAt(int i, int j){

System.out.println("The value of cell("+i+","+j+")is "+linkedList[i-1].get(j-1));

return linkedList[i-1].get(j-1);

}

public static void deleteAt(int i, int j){

linkedList[i-1].remove(j-1);

System.out.print("delete cell("+i+","+j+")");

}

public static void printRow(int row){

for(int i=0;i<N;i++){

System.out.print(linkedList[row-1].get(i)+" ");

}

System.out.println();

}

public static void printCol(int col){

for(int i=0;i<M;i++){

System.out.print(linkedList[i].get(col-1)+" ");

}

System.out.println();

}

public static void main(String[] args) {

Scanner sc= new Scanner(System.in);

System.out.println("Enter Ma nd N ");

M=sc.nextInt();

N=sc.nextInt();

linkedList = new LinkedList[M];

for(int i=0;i<M;i++)

linkedList[i] = new LinkedList<Integer>();

for(int i=0;i<M;i++)

for(int j=0;j<N;j++)

linkedList[i].add(0);

insertAt(10,3,2);

insertAt(20,2,3);

insertAt(30,1,1);

insertAt(40,2,2);

printRow(2);

printCol(2);

deleteAt(2,3);

getValueAt(2,3);

getValueAt(3,2);

}

}