public class SinglyLinkedList {


private Node head = null;

private Node tail = null;

private int size = 0;


private class Node {


private Node next;

private Object data;


public Node(Object input) {

this.data = input;

this.next = null;

}// Node.Constructor


}// class Node


public void addFirst(Object input) {

Node newNode = new Node(input);

if (head == null) {

head = newNode;

tail = head;

} else {

newNode.next = head;

head = newNode;

}

size++;

System.out.print(input + " is added as the first element. ");

print();

}// SinglyLinkedList.addFirst


public void addLast(Object input) {

Node newNode = new Node(input);

if (tail == null) {

tail = newNode;

head = tail;

} else {

tail.next = newNode;

tail = newNode;

}

size++;

System.out.print(input + " is added as the last element. ");

print();

}// SinglyLinkedList.addLast


public void add(int k, Object input) {

if (k == 0) {

addFirst(input);

} else if (k == size) {

addLast(input);

} else {

Node newNode = new Node(input);

Node x = node(k - 1);

newNode.next = x.next;

x.next = newNode;

size++;

System.out.print(input + " is added in the list. ");

print();

}

}// SinglyLinkedList.add

public Node node(int index) {

Node x = head;

for (int i = 1; i <= index; i++) {

x = x.next;

}

return x;

}// SinglyLinkedList. node


public void print() {

if (head != null) {

System.out.print("list = [ ");

Node x = head;

while (true) {

System.out.print(x.data);

if (x == tail)

break;

else

System.out.print(", ");

x = x.next;

}

System.out.print(" ]");

System.out.print(System.lineSeparator());

} else {

System.out.print("list is now empty.");

}

}// SinglyLinkedList.print


public Object removeFirst() {

Object removedData = head.data;

head = head.next;

size--;

System.out.print(removedData + " is removed in the list. ");

print();

return removedData;

}// SinglyLinkedList.removeFirst


public Object removeLast() {

Object removedData = tail.data;

node(size - 2).next = null;

tail = node(size - 2);

size--;

System.out.print(removedData + " is removed in the list. ");

print();

return removedData;

}// SinglyLinkedList.removeLast

public Object remove(int k) {

Object removedData = node(k).data;

if (node(k) == head) {

removeFirst();

} else if (node(k) == tail) {

removeLast();

} else {

node(k - 1).next = node(k).next;

System.out.print(removedData + " is removed in the list. ");

print();

size--;

}

return removedData;

}// SinglyLinkedList.remove



public int size() {

return size;

}// SinglyLinkedList.size


public Object get(int k) {

Object data = node(k).data;

return data;

}// SinglyLinkedList.get


public int indexOf(Object data) {

Node x = head;

for(int i = 0; i < size; i++) {

if(x.data == data) 

return i;

x = x.next;

}

return -1;

}// SinglyLinkedList.indexOf


}// class SinglyLinkedList