Home > Back-end >  How adding element to Linked List
How adding element to Linked List

Time:10-22

I'm trying to understand the behavior of on how the elements of a String[] contentsOfBag are added into a linkedbag which is csc220bag (for this programming case).

First concern: from my understanding, each elements of String[] contentsOfBag are added such as element "A" goes into a Node with the data "A". Inside this same Node we have another Node where the next element "_" will be the data of this next Node and so on? Please correct me if I'm wrong/not totally correct.

Second concern is the purpose of constructor "private Node(T dataPortion)" & " private Node(T dataPortion, Node nextNode)" ?

It'll be very helpful for my understanding since I need to implement removeAllOccurences method. Ty

Here is the code : Driver Code

public class LinkedBagCSC220JavaDriver {

public static void main(String[] args) {
    System.out.println("=== LINKED BAG 220 JAVA ==========================================================");
    System.out.println("[ ] Creating a CSC220 LinkedBag...");
    PrimaryDataStructureBagInterface<String> csc220Bag = new LinkedBag<>();
    testAdd(csc220Bag);
    testRemoveAllOccurrences(csc220Bag);
    System.out.println("=== LINKED BAG 220 JAVA ==========================================================");
}

private static void displayBag(PrimaryDataStructureBagInterface<String> aBag) {
    System.out.print("[>] The bag now contains "   aBag.getCurrentSize()   " string(s): \t");
    Object[] bagArray = aBag.toArray();
    for (Object bagArray1 : bagArray) {
        System.out.print(bagArray1   " ");
    }
    System.out.println();
}

private static void testRemoveAllOccurrences(PrimaryDataStructureBagInterface<String> aBag) {
    // Removing all occurrences of the given entries from a bag
    System.out.println("[ ] Creating... a 2D test array with the below contents: \t");
    String[][] testArray = {
            { "A", "A", "A", "A", "A", "A" },
            { "B", "A", "Bb", "B", "Bb", "B" },
            { "C", "B", "_", "A" },
            { "n", "u", "l", "l" }
    };

    for (String[] row : testArray) {
        System.out.print("\t\t\t\t\t");
        for (String col : row) {
            System.out.print(col   " ");
        }
        System.out.println("");
    }

    aBag.removeAllOccurrences(testArray);
    displayBag(aBag);
}

private static void testAdd(PrimaryDataStructureBagInterface<String> aBag) {
    // Adding strings
    String[] contentsOfBag = {
            "A", "_", "_", "G", "Bb", "A", "_", "u", "n",
            "o", "A", "o", "d", "Bb", "A", "A", "l", "l"
    };
    System.out.print("[ ] Adding.... these items to the bag: \t");
    for (String entry : contentsOfBag) {
        aBag.add(entry); // trying to understand behind the scene of this line
        System.out.print(entry   " ");
    }
    System.out.println();

    displayBag(aBag);
}

}

Linkedbag

public final class LinkedBag<T> implements PrimaryDataStructureBagInterface<T> {

private Node firstNode;
private int numberOfEntries;

public LinkedBag() {
    firstNode = null;
    numberOfEntries = 0;
}

@Override
public boolean removeAllOccurrences(T[][] entries) {
}

private class Node {
    private T data;
    private Node next;

    private Node(T dataPortion) {
        this(dataPortion, null);
    } // end constructor

    private Node(T dataPortion, Node nextNode) {
        data = dataPortion;
        next = nextNode;
    }
}

}

Interface class - PrimaryDataStructureBagInterface

public interface PrimaryDataStructureBagInterface<T> {

public int getCurrentSize();

public boolean isEmpty();

public boolean add(T newEntry);

public boolean removeAllOccurrences(T[][] entries);

public T[] toArray();

}

CodePudding user response:

To address your first concern: you are correct.

To address your second concern: the private constructors are to limit where Node can be created.

like so

public class Test {
    public Inner createInner(){
        return new Inner();
    }

    public class Inner{
        private Inner(){
            System.out.println("creating inner");
        }
    }
}
public class main{
    public static void main(String[] args) {
        //works
        Test t = new Test();
        t.createInner();

        //wont work
        main.Test.Inner inner = new Test.Inner();
    }
}

CodePudding user response:

First concern: from my understanding, each elements of String[] contentsOfBag are added such as element "A" goes into a Node with the data "A". Inside this same Node we have another Node where the next element "_" will be the data of this next Node and so on? Please correct me if I'm wrong/not totally correct.

This is correct.

aBag.add(entry); // trying to understand behind the scene of this line

This method call is of a method inside the LinkedBag class, which you haven't shown the implementation of, but it should traverse the LinkedBag list starting from the 'firstNode' reference inside of LinkedBag, going through the 'next' reference inside of Node class, until the loop reaches the last node (node.next == null). There, you set the 'next' variable to this new 'entry'. And that's how each entry in the array is inserted.

It'll be very helpful for my understanding since I need to implement removeAllOccurences method. Ty

To remove all entries housed in the array, you need to loop the array element by element, and for each element you need to compare that element with each element in the LinkedBag. If that element matches anything in the LinkedBag chain of bags, then you break that reference by making the previous node point to the later node. This diagram should help you visualize the deletion process:

linkedBag (firstNode) -> bag1 (data="chips",next=bag2) -> bag2 (data="mayo",next=bag3) -> bag3 (data="dip",next=null)

If the array passed to the removeAllOccurences method has a "dip" element, in order to remove it, the removeAllOccurences method would have to loop through the list and compare each element's data with "dip". Once it reaches the bag3 object, it will find that it is in fact "dip". In order to remove it, you'd need to cut off the 'next' reference inside of bag2 (make it null). To do that, you would need 'previous' and 'current' pointers. At that point, 'previous' would be on bag2. So, you simply do:

previous.next = null;

Lastly, it would help you better understand LinkedList's add/remove methods if you visualize them. Draw on paper, watch some visualizations on YouTube, and read an article about it, like this.

  •  Tags:  
  • java
  • Related