In: Computer Science
Hi, I would like to test a java program. I am learning linked list and going to make a linked lists for integer nodes.
For instance, I am going to add the numbers 12, 13, and 16 to the list and then display the list contents
and add 15 to the list again and display the list contents and delete 13 from the list
and display the list contents and lastly delete 12 from the list and display the list contents
In order to test like this, with this reference below how can I make a simple code?
If you can please include comments to catch up the codes, it would help me a lot!
public class IntegerNode {
private int item;
private IntegerNode next;
public IntegerNode(int newItem) {
item = newItem;
next = null;
} // end constructor
public IntegerNode(int newItem, IntegerNode nextNode) {
item = newItem;
next = nextNode;
} // end constructor
public void setItem(int newItem) {
item = newItem;
} // end setItem
public int getItem() {
return item;
} // end getItem
public void setNext(IntegerNode nextNode) {
next = nextNode;
} // end setNext
public IntegerNode getNext() {
return next;
} // end getNext
} // end class IntegerNode
Sample program :
import java.util.LinkedList;
public class IntegerNode {
public static void main(String args[])
{
// Creating an empty LinkedList
LinkedList<String> list = new
LinkedList<String>();
// Use add() method to add elements in the list
list.add("12");
list.add("13");
list.add("16");
// Displaying the linkedlist
System.out.println("LinkedList:" + list);
// Using set() method to replace Geeks with GFG
System.out.println("The Object that is replaced is: " +
list.add("15"));
System.out.println("LinkedList:" + list);
// Using set() method to replace 20 with 50
System.out.println("The Object that is replaced is: " +
list.remove(1));
// Displaying the modified linkedlist
System.out.println("The new LinkedList is:" + list);
System.out.println("The Object that is replaced is: " +
list.remove(0));
System.out.println("The new LinkedList is:" + list);
}
}
As per your question above, this program will help you to understand the linked List follow of work. If you need more clarification from the linkedlist comment with your need full question.