Exercise 2- Singly Linked Lists 1. Open LinearNode.java and BuildLinkedList.java in Eclipse and examine the code in both
Posted: Sun Jul 10, 2022 11:25 am
-------
public class BuildLinkedList {
/* * Print the information stored in all the nodesof the list whose first node is * referenced by front */ private static voidprintList(LinearNode<Integer> front) { LinearNode<Integer>current = front; for (int i = 1; i <= 10;i++) { System.out.println(current.getElement()); current =current.getNext(); } }
public static void main(String[] args) {
// create a linked listthat holds 1, 2, ..., 10 // by starting at 10 andadding each node at head of list
LinearNode<Integer>front = null; // create empty linked list LinearNode<Integer>intNode;
for (int i = 10; i >=1; i--) { // createa new node for i intNode =new LinearNode<Integer>(new Integer(i)); // add itat the head of the linked list intNode.setNext(front); front =intNode; }
printList(front); }
}
Exercise 2- Singly Linked Lists 1. Open LinearNode.java and BuildLinkedList.java in Eclipse and examine the code in both classes. 2. The main () method in BuildLinked List created a list with 10 nodes, each storing an integer value from 1 to 10. The printList() method prints out this list. Run the program to see the list elements printed out. 3. The problem is that printList() is "hard-coded" to loop through 10 elements in the for-loop so this method will not work for any other size of list. Modify this method so that it works for any list length (i.e. not hard-coded). You cannot change the method signature (parameters). You also cannot add instance variables to the class. 4. In the main() method, change the for-loop to create a list of 20 nodes and run the program to ensure that it correctly creates and prints out those 20 nodes. 5. Change it again, this time to 7 and check that it works properly with the 7 nodes.