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

NODE CLASS: Using the Node class, write a driver program called LinkedListIntro

ID: 3567302 • Letter: N

Question

NODE CLASS:

Using the Node class, write a driver program called LinkedListIntro where you create the following linked list using Integers: Write a method that uses a loop to print out the linked list with commas, like this: [1, 2, 3, 4, 5] . Call the method you wrote in step 2 to display your list. Now use a temporary node point to REMOVE the node containing a 4 from the linked list. Call the method you wrote in step 2 to display your list. It should look like: [1, 2, 3, 5] Now add a new node with a 100 in it between the 1 and the 2. Call the method you wrote in step 2 to display your list. It should look like: [1, 100, 2, 3, 5] Now remove the very first node (the one with a 1 in it) and print your list. It should look like: [100, 2, 3, 5] Finally, add a new node to the very beginning of the list with a 0 in it and print your list. It should look like: [0, 100, 2, 3, 5]

Explanation / Answer

public class LinkedListIntro {

public static void print(Node temp)
{
System.out.print("[");
while(temp.getNext() != null)
{
System.out.print(temp.getData()+", ");
temp = temp.getNext();
}
System.out.println(temp.getData()+"]");
}
public static void main(String[] args) {
  
Node start = null;
Node temp = null;
  
for(int i=1; i<=5; i++)
{
if(start == null)
{
start = new Node(i);
temp = start;
}
else
{
temp.setNext(new Node(i));
temp = temp.getNext();
}
}
  
print(start); //3. printing data
  
//4. removing 4
  
temp = start;
Node n = temp.getNext();
  
while(n.getNext() != null)
{
if((int)n.getData() == 4)
{
temp.setNext(n.getNext());
n=null;
break;
}
temp = temp.getNext();
n=n.getNext();
}
  
print(start); //5. printing data again after removing 4
  
//6. adding 100 between 1 and 2
  
temp = start;
Node n1 = temp.getNext();
  
while(n1.getNext() != null)
{
if((int)temp.getData() == 1)
{
temp.setNext(new Node(100));
temp = temp.getNext();
temp.setNext(n1);
}
temp = temp.getNext();
n1=n1.getNext();
}
  
print(start); //7. printing data again after adding 100
  
//8. removing first node
temp = start;
start = start.getNext();
temp = null;
  
print(start); //printing data after removing 1st node
  
//9. add 0 to beginning
  
temp = start;
start = new Node(0);
start.setNext(temp);
  
print(start); //printting the final data
  
  
}
  
}