-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedListExample.java
More file actions
56 lines (47 loc) · 1.28 KB
/
Copy pathLinkedListExample.java
File metadata and controls
56 lines (47 loc) · 1.28 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
public class LinkedListExample {
public static void main(String[] args) {
LinkedList list = new LinkedList();
// Adding numbers to the linked list
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
// Displaying the linked list
list.display();
}
}
class LinkedList {
Node head;
// Node class representing each element in the linked list
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
// Method to add a new element to the linked list
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node currentNode = head;
while (currentNode.next != null) {
currentNode = currentNode.next;
}
currentNode.next = newNode;
}
}
// Method to display the linked list
public void display() {
Node currentNode = head;
System.out.print("Linked List: ");
while (currentNode != null) {
System.out.print(currentNode.data + " ");
currentNode = currentNode.next;
}
}
}