public class LinkedList {
Node head;
Node tail;
int length;
LinkedList(int value){
head = new Node(value);
tail=head;
length=1;
}
public void append(int value){
Node newNode = new Node(value);
tail.next = newNode;
tail=newNode;
length++;
}
public void prepend(int value){
Node newNode = new Node(value);
newNode.next= head;
head=newNode;
length++;
}
public void printList(LinkedList myLinkedList){
int i=1;
Node currentNode= myLinkedList.head;
while(i<=myLinkedList.length){
System.out.print(currentNode.value + " ");
currentNode = currentNode.next;
i++;
}
System.out.println();
}
public void insert(int index, int value){
if(index==0){
prepend(value);
}
else if(index==length){
append(value);
}
else{
Node currentNode = this.head;
int i = 0;
while(i<index-1 && currentNode!= null){
currentNode=currentNode.next;
i++;
}
Node newNode = new Node(value);
newNode.next=currentNode.next;
currentNode.next= newNode;
this.length++;
}
}
public void remove(int index){
if (index < 0 || index > length) {
System.err.println("Index Out Of Bounds For Length " + length);
} else if (index == 0) {
head = this.head.next;
length--;
} else {
Node current = head;
int i;
for (i = 0; i < index - 1; i++) {
current = current.next;
}
current.next = current.next.next;
length--;
if (i == length - 1) {
tail = current;
}
}
}
public static void main(String[] args) {
LinkedList myLinkedList = new LinkedList(10);
myLinkedList.append(5);
myLinkedList.append(6);
myLinkedList.prepend(15);
myLinkedList.printList(myLinkedList);
myLinkedList.insert(2, 25);
myLinkedList.printList(myLinkedList);
myLinkedList.remove(2);
myLinkedList.printList(myLinkedList);
}
}
class Node{
int value;
Node next;
Node(int value){
this.value = value;
this.next=null;
}
}
//10-->5-->1-->3