In: Computer Science
Create a generic Linked List that does NOT use the Java library linked list. Make sure it contains or access a subclass named Node (also Generic). And has the methods: addFirst(), addLast(), add(), removeFirst(), removeLast() and getHead(). In a separate Java class provide a main that creates an instance of your LinkedList class that creates an instance of your LinkedList that contains String types. Add the five names (you pick them) to the list and then iterate through the list to print all the names.
import java.io.*;
class Node <T>{
T data;
Node next;
// Constructor
Node(T d)
{
data = d;
next = null;
}
}
// Java program to implement
// a Singly Linked List
class LinkedList <T>{
Node head=null,tail=null;
void addFirst(T val) {
if(head==null) {
head = tail =new Node(val);
}else {
Node temp=head;
head = new Node(val);
head.next = temp;
}
}
void addLast(T val) {
if(head==null) {
head = tail =new Node(val);
}else {
tail.next = new Node(val);
tail = tail.next;
}
}
void removeFirst() {
if(head==null) {
return;
}
head= head.next;
}
void removeLast() {
if(head==null) {
return;
}
Node temp=head;
while(temp.next.next!=null) {
temp = temp.next;
}
tail = temp;
}
T getHead() {
return (T) head.data;
}
void printList() {
Node temp=head;
while(temp!=null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
}
class Main{
// **************MAIN METHOD**************
public static void main(String[] args)
{
LinkedList<String> list = new LinkedList<String>();
list.addFirst("Jack");
list.addLast("Heron");
list.addFirst("Steve");
list.addLast("Carla");
list.addFirst("John");
list.printList();
}
}
OUTPUT: