Upload files to "OOP/Java/Lab/Week12"
This commit is contained in:
parent
2ae5d58f75
commit
100e80ccc3
5 changed files with 226 additions and 0 deletions
66
OOP/Java/Lab/Week12/GenList.java
Normal file
66
OOP/Java/Lab/Week12/GenList.java
Normal file
|
@ -0,0 +1,66 @@
|
|||
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");
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue