-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathHelloWorld.java
44 lines (37 loc) · 1.14 KB
/
HelloWorld.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
public class HelloWorld {
private Node head;
// Method to insert a new node at the beginning of the linked list
public void insertAtBeginning(int data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
// Method to display the elements of the linked list
public void displayList() {
Node current = head;
System.out.print("Linked List: ");
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}
public static void main(String[] args) {
SinglyLinkedList linkedList = new SinglyLinkedList();
// Insert nodes at the beginning
linkedList.insertAtBeginning(3);
linkedList.insertAtBeginning(5);
linkedList.insertAtBeginning(7);
linkedList.insertAtBeginning(9);
// Display the linked list
linkedList.displayList();
}
}