public interface SortedList {
void insert(int element);
void delete(int element);
void deleteAll(int element);
boolean search(int element);
void print();
}
package [Link];
public class SortedLinkedList implements SortedList {
class Node {
int data;
Node next;
public Node() {
data = 0;
next = null;
}
public Node(int data) {
[Link] = data;
next = null;
}
}
Node head;
public SortedLinkedList() {
head = null;
}
@Override
public void insert(int ele) {
Node newNode = new Node(ele); // Create a new node
if (head == null) { // List is empty
head = newNode;
return;
}
Node current = head;
Node previous = null;
// Find the correct insertion point
while (current != null && [Link] <= [Link]) {
previous = current;
current = [Link];
}
if (previous == null) { // Insert at the beginning
[Link] = head;
head = newNode;
} else { // Insert between previous and current
[Link] = newNode;
[Link] = current;
}
}
@Override
public void delete(int ele) {
Node current = head;
Node previous = null;
// Special case: deleting the head node
if (current != null && [Link] == ele) {
head = [Link]; // Move head to the next node
return;
}
// Traverse to find the element to delete
while (current != null) {
if ([Link] == ele) {
[Link] = [Link]; // Bypass the current node
return;
}
previous = current;
current = [Link];
}
[Link]("Element is not present"); // Element not found
}
@Override
public void deleteAll(int ele) {
if (head == null) {
[Link]("List is empty");
return;
}
// Remove occurrences at the head
while (head != null && [Link] == ele) {
head = [Link]; // Update head to skip nodes with the value 'ele'
}
Node current = head;
Node previous = null;
// Traverse the list to delete all occurrences
while (current != null) {
if ([Link] == ele) {
[Link] = [Link]; // Bypass the current node
} else {
previous = current; // Move previous only if not deleted
}
current = [Link]; // Move to the next node
}
}
@Override
public boolean search(int ele) {
if (head == null) {
[Link]("List is empty");
return false;
}
Node current = head;
// Traverse the list to search for the element
while (current != null) {
if ([Link] == ele) {
return true; // Element found
}
current = [Link]; // Move to the next node
}
return false; // Element not found
}
@Override
public void print() {
Node current = head;
while (current != null) {
[Link]([Link]); // Print current node's data
current = [Link]; // Move to the next node
}
}
}
public class tester {
public static void main(String[] args) {
SortedLinkedList list = new SortedLinkedList();
[Link](0);
[Link](44);
[Link](55);
[Link](66);
[Link](0);
[Link](44);
[Link](77);
[Link](44);
//[Link](0);
[Link](44);
//[Link](44);
[Link]();
[Link]( [Link](12));
}
}