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

I hope to answer with java language Create a LinkedList using Java library class

ID: 3763352 • Letter: I

Question

I hope to answer with java language

Create a LinkedList using Java library class and add the following strings Diana, Harry, Romeo, Tom and then remove first string from the LinkedList. Write Java code for methods addFirst() and removeFirstf) for a LinkedList. Write a java program where you declare and use a Queue and a Stack. use the library methods: for a stack use push and pop, for a queue add Declare a queue called "q" and load it with the integers: 10, 20, 30 Display the queue by printing it. Remove the first node of the queue, display the queue size, display the queue head after the remove. Declare a stack called "s" and load it with the integers: 100, 200, 300 Display the stack by printing it. Remove a node from the stack, display the stack size, display the stack top after the remove.

Explanation / Answer

1)

listdemo.java
import java.util.LinkedList;
import java.util.ListIterator;

/**
This program demonstrates the LinkedList class.
*/
public class ListDemo
{
public static void main(String[] args)
{
LinkedList<String> staff = new LinkedList<String>();
staff.addLast("Diana");
staff.addLast("Harry");
staff.addLast("Romeo");
staff.addLast("Tom");

// | in the comments indicates the iterator position

ListIterator<String> iterator = staff.listIterator(); // |DHRT
iterator.next(); // D|HRT
iterator.next(); // DH|RT

// Add more elements after second element

iterator.add("Juliet"); // DHJ|RT
iterator.add("Nina"); // DHJN|RT
iterator.next(); // DHJNR|T
// Remove last traversed element
iterator.remove(); // DHJN|T
  
// Print all elements

System.out.println(staff);
System.out.println("Expected: [Diana, Harry, Juliet, Nina, Tom]");
}
}

program run
[Diana, Harry, Juliet, Nina, Tom]
Expected: [Diana, Harry, Juliet, Nina, Tom]


2)

import java.util.*;
class LinkedList
{
public static void main(String args[])
{
// create a linked list
LinkedList ll = new LinkedList();
// add elements to the linked list
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents of ll: " + ll);
// remove elements from the linked list
ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion: "
+ ll);
// remove first and last elements
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last: " + ll);
// get and set a value
Object val = ll.get(2);
ll.set(2, (String) val + " Changed");
System.out.println("ll after change: " + ll);
}
}