//Single linked list implementation
public class Nodes {
int data;
Nodes next = null;
public Nodes(int data) {
this.data = data;
}
}
public class Lists {
static Nodes first = null;
public static void insertBegin(int data) {
Nodes temp = new Nodes(data);
if(first == null) {
first = temp;
}
else {
temp.next = first;
first = temp;
}
}
public static void insertEnd(int data) {
Nodes temp = new Nodes(data);
if(first == null) {
first = temp;
}
else{
Nodes n = first;
while(n.next != null) {
n = n.next;
}
n.next = temp;
}
}
public static void insertPos(int pos, int data) {
Nodes temp = new Nodes(data);
if(first == null) {
System.out.println("List empty. Cannot insert");
}
else {
Nodes n = first;
while(n.data != pos && n.next != null) {
n = n.next;
}
if(n.data != pos){
System.out.println("Position not found");
}
else {
temp.next = n.next;
n.next = temp;
}
}
}
public static void deleteBegin() {
if(first == null) {
System.out.println("List empty. Cannot delete");
}
else {
first = first.next;
}
}
public static void deleteEnd() {
if(first == null) {
System.out.println("List empty. Cannot delete");
}
else {
Nodes n = first;
while(n.next.next != null) {
n = n.next;
}
n.next = n.next.next;
}
}
public static void deletePos(int pos) {
if(first == null) {
System.out.println("List empty. Cannot delete");
}
else {
Nodes n = first;
while(n.next.data != pos && n.next.next != null) {
n = n.next;
}
if(n.next.data != pos) {
System.out.println("Element not found. Deletion failed");
}
else{
n.next = n.next.next;
}
}
}
public static void printAll() {
System.out.println("Elements in link list");
Nodes n = first;
while(n != null) {
System.out.print(n.data + "->");
n = n.next;
}
}
}