-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList.java
More file actions
102 lines (91 loc) · 2.26 KB
/
Copy pathLinkedList.java
File metadata and controls
102 lines (91 loc) · 2.26 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package project;
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public class LinkedList {
private Node head;
// Insert at the beginning
void insertAtBeginning(int data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
// Insert at the end
void insertAtEnd(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
// Insert after a specific key
void insertAfter(int key, int data) {
Node temp = head;
while (temp != null && temp.data != key) {
temp = temp.next;
}
if (temp != null) {
Node newNode = new Node(data);
newNode.next = temp.next;
temp.next = newNode;
} else {
System.out.println("Key " + key + " not found.");
}
}
// Delete at the beginning
void deleteAtBeginning() {
if (head != null) {
head = head.next;
}
}
// Delete at the end
void deleteAtEnd() {
if (head == null) return;
if (head.next == null) {
head = null;
return;
}
Node temp = head;
while (temp.next.next != null) {
temp = temp.next;
}
temp.next = null;
}
// Delete by key
void deleteByKey(int key) {
if (head == null) return;
if (head.data == key) {
head = head.next;
return;
}
Node temp = head;
while (temp.next != null && temp.next.data != key) {
temp = temp.next;
}
if (temp.next != null) {
temp.next = temp.next.next;
} else {
System.out.println("Key " + key + " not found.");
}
}
// Display the list
void display() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " -> ");
temp = temp.next;
}
System.out.println("null");
System.out.println();
}
}