Skip to content

Commit 3726c0c

Browse files
authored
Merge pull request csubhasundar#224 from Raksha703/LinkedList
Create LinkedList.java
2 parents 71b5326 + 2126bc9 commit 3726c0c

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

java/LinkedList.java

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
class Node {
2+
int data;
3+
Node next;
4+
5+
public Node(int data) {
6+
this.data = data;
7+
this.next = null;
8+
}
9+
}
10+
11+
class LinkedList {
12+
Node head;
13+
14+
public LinkedList() {
15+
this.head = null;
16+
}
17+
18+
public void insert(int data) {
19+
Node newNode = new Node(data);
20+
if (head == null) {
21+
head = newNode;
22+
} else {
23+
Node current = head;
24+
while (current.next != null) {
25+
current = current.next;
26+
}
27+
current.next = newNode;
28+
}
29+
}
30+
31+
public void delete(int data) {
32+
if (head == null) {
33+
System.out.println("List is empty.");
34+
return;
35+
}
36+
if (head.data == data) {
37+
head = head.next;
38+
return;
39+
}
40+
Node current = head;
41+
while (current.next != null) {
42+
if (current.next.data == data) {
43+
current.next = current.next.next;
44+
return;
45+
}
46+
current = current.next;
47+
}
48+
System.out.println("Element not found in the list.");
49+
}
50+
51+
public void display() {
52+
if (head == null) {
53+
System.out.println("List is empty.");
54+
return;
55+
}
56+
Node current = head;
57+
System.out.print("Linked List: ");
58+
while (current != null) {
59+
System.out.print(current.data + " ");
60+
current = current.next;
61+
}
62+
System.out.println();
63+
}
64+
}
65+
66+
public class LinkedListExample {
67+
public static void main(String[] args) {
68+
LinkedList linkedList = new LinkedList();
69+
linkedList.insert(5);
70+
linkedList.insert(10);
71+
linkedList.insert(15);
72+
linkedList.display();
73+
74+
linkedList.delete(10);
75+
linkedList.display();
76+
77+
linkedList.delete(20);
78+
}
79+
}

0 commit comments

Comments
 (0)