MIT-Curricular/OOP/Java/Lab/Week12/GenList.java

67 lines
1.4 KiB
Java
Raw Normal View History

2024-10-26 02:14:18 +05:30
public class SinglyLinkedListDemo {
public static void main(String[] args) {
// Test with Integer
SinglyLinkedList<Integer> intList = new SinglyLinkedList<>();
intList.add(10);
intList.add(20);
intList.add(30);
System.out.println("Integer List:");
intList.printList();
// Test with Double
SinglyLinkedList<Double> doubleList = new SinglyLinkedList<>();
doubleList.add(1.1);
doubleList.add(2.2);
doubleList.add(3.3);
System.out.println("\nDouble List:");
doubleList.printList();
}
}
class SinglyLinkedList<T> {
private class Node {
T data;
Node next;
Node(T data) {
this.data = data;
this.next = null;
}
}
private Node head;
public SinglyLinkedList() {
head = null;
}
public void add(T data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
public void printList() {
Node current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}
}