-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList.java
More file actions
116 lines (94 loc) · 2.65 KB
/
LinkedList.java
File metadata and controls
116 lines (94 loc) · 2.65 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
public class LinkedList {
// Node inner class
private class Node {
Student student;
Node next;
Node(Student student) {
this.student = student;
this.next = null;
}
}
private Node head;
public LinkedList() {
head = null;
}
// Add Student (at end) with duplicate ID check
public void Add(Student student) {
if (Search(student.getId()) != null) {
throw new IllegalArgumentException("Student with ID " + student.getId() + " already exists.");
}
Node newNode = new Node(student);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
// Search Student by ID
public Student Search(int id) {
Node current = head;
while (current != null) {
if (current.student.getId() == id) {
return current.student;
}
current = current.next;
}
return null;
}
// Update Student
public boolean Update(int id, String name, String grade, String attendance) {
Node current = head;
while (current != null) {
if (current.student.getId() == id) {
current.student.setName(name);
current.student.setGrade(grade);
current.student.setAttendance(attendance);
return true;
}
current = current.next;
}
return false;
}
// Delete Student by ID
public boolean Delete(int id) {
if (head == null) return false;
if (head.student.getId() == id) {
head = head.next;
return true;
}
Node current = head;
while (current.next != null) {
if (current.next.student.getId() == id) {
current.next = current.next.next;
return true;
}
current = current.next;
}
return false;
}
// Get all students as array
public Student[] GetAll() {
int count = 0;
Node current = head;
while (current != null) {
count++;
current = current.next;
}
Student[] arr = new Student[count];
current = head;
int i = 0;
while (current != null) {
arr[i++] = current.student;
current = current.next;
}
return arr;
}
// Check empty
public boolean isEmpty() {
return head == null;
}
}