public class Test {
public static void main(String[] args) {
SinglyLinkedList list = new SinglyLinkedList(); // {null}
list.insertToHead(5); // {5} -> {null}
list.insertToTail(1); // {5} -> {1} -> {null}
list.insertToHead(2); // {2} -> {5} -> {1} -> {null}
list.insertToTail(3); // {2} -> {5} -> {1} -> {3} -> {null}
list.deleteAt(3);
list.deleteAt(5);
list.deleteAt(1);
list.deleteAt(1);
list.deleteAt(1);
list.deleteAt(2);
list.deleteAt(2);
list.traverse();
}
}
class SinglyLinkedList {
Node head;
void insertToHead(int value) {
Node newNode = new Node(value);
newNode.next = head;
head = newNode;
}
void insertToTail(int value) {
Node newNode = new Node(value);
if (head == null){
head = newNode;
} else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
}
void insertAt(int data, int value) {
Node temp = head;
Node newNode = new Node(value);
if (head == null) {
head = newNode;
} else {
while(temp.next != null) {
if (temp.data == data) {
newNode.next = temp.next;
temp.next = newNode;
}
temp = temp.next;
}
}
}
void deleteHead() {
if (head != null) {
head = head.next;
}
}
void deleteTail() {
if (head == null) {
// wala
} else if (head.next == null) {
head = head.next;
} else {
Node temp = head;
Node prev = null;
while (temp.next != null) {
prev = temp;
temp = temp.next;
}
prev.next = null;
}
}
void deleteAt(int data) {
Node temp = head;
Node prev = null;
if (head == null){
System.out.println("list is empty");
} else if (temp.data == data) {
deleteHead();
} else {
while(temp.next != null) {
if (temp.data == data) {
prev.next = temp.next;
}
prev = temp;
temp = temp.next;
}
if (temp.data == data) {
prev.next = temp.next;
}
}
}
void traverse() {
Node temp = head;
while (temp != null) {
System.out.println(temp.data);
temp = temp.next;
}
}
}
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
}