I am trying to write a simple linked list class that uses generic data type. I am new to Java so I can't figure out how to debug the error message in the main method that arises when I try to insert data into an instance of my class. The class code and the main method are as follows:
import java.io.*;
// Java program to implement
// a Singly Linked List
public class MyLinkedList<T> {
Node head; // head of the list
class Node<T> {
T data;
Node next;
// Constructor
Node(T d)
{
data = d;
next = null;
}
}
// Method to insert a new node
MyLinkedList insert(MyLinkedList list, T data)
{
// Create a new node with given data
Node new_node = new Node(data);
new_node.next = null;
// If the Linked List is empty,
// then make the new node as head
if (list.head == null) {
list.head = new_node;
}
else {
// Else traverse till the last node
// and insert the new_node there
Node last = list.head;
while (last.next != null) {
last = last.next;
}
// Insert the new_node at last node
last.next = new_node;
}
// Return the list by head
return list;
}
// Driver code
public static void main(String[] args)
{
/* Start with the empty list. */
MyLinkedList list = new MyLinkedList();
// Insert the values
list = insert(list, 1);
}
}
You need to change int to T in class declaration and method signature.
class MyLinkedList<T> {
MyLinkedList() {
head=null;
}
Node head; // head of list
class Node<T> {
T data;
Node next;
// Constructor
Node(T d) {
data = d;
next = null;
}
}
// Method to insert a new node
public void insert(T data) {
// Create a new node with given data
Node new_node = new Node(data);
new_node.next = null;
// If the Linked List is empty,
// then make the new node as head
if (this.head == null) {
this.head = new_node;
} else {
Node last = this.head;
while (last.next != null) {
last = last.next;
}
// Insert the new_node at last node
last.next = new_node;
}
}
protected void display() {
Node myNode=head;
System.out.println();
while (myNode != null) {
System.out.println(myNode.data);
myNode=myNode.next;
}
}
Change the insert method signature to the below:
public static void main(String[] args) {
/* Start with the empty list. */
MyLinkedList<Integer> list = new MyLinkedList<Integer>();
// Insert the values
list.insert(1);
list.insert(3);
list.insert(12);
list.insert(11);
list.insert(21);
list.insert(22);
list.insert(45);
list.display();
}
For clear coding and understanding I have changed class name as MyLinkedList