public class LinkedList {
int size;
ListNode head;
public LinkedList() {
head = new ListNode();
head.next = head;
head.prev = head;
size = 0;
}
private ListNode addBefore(int x, ListNode bantu) {
ListNode baru = new ListNode(x);
baru.next = bantu;
baru.prev = bantu.prev;
bantu.prev.next = baru;
bantu.prev = baru;
size++;
return baru;
}
private int remove(ListNode bantu) {
if (isEmpty()) {
System.out.println("Senarai Kosong");
} else {
bantu.next.setPrev(bantu.getPrev());
bantu.prev.setNext(bantu.getNext());
bantu.setNext(null);
bantu.setPrev(null);
}
size--;
return bantu.getElement();
}
public void addFirst(int x) {
addBefore(x, getHead().getNext());
}
public void addLast(int x) {
addBefore(x, getHead());
}
public int removeFirst() {
return remove(getHead().getNext());
}
public int removeLast() {
return remove(getHead().getPrev());
}
public int remove(int x) {
ListNode bantu = head;
if (isEmpty()) {
System.out.println("Senarai kosong");
} else {
while (bantu.next != head) {
bantu = bantu.next;
if (bantu.element == x) {
remove(bantu);
break;
}
}
}
return bantu.element;
}
public void addSort(int x) {
if (isEmpty()) {
addBefore(x, head.next);
} else {
ListNode bantu = head.next;
while (bantu != head && x > bantu.element) {
bantu = bantu.next;
}
addBefore(x, bantu);
}
}
public String toString() {
String string = new String();
ListNode bantu = head;
while (bantu.next != head) {
bantu = bantu.next;
string += bantu.element + " ";
}
if (isEmpty()) {
return "Senarai Kosong";
} else {
return string;
}
}
public void display() {
ListNode bantu = head;
while (bantu.next != head) {
bantu = bantu.next;
System.out.println(bantu.element);
}
}
public ListNode search(int x) {
ListNode bantu = head;
while (bantu.next != head) {
bantu = bantu.next;
if (bantu.element == x) {
return bantu;
}
}
System.out.println("Tidak ditemukan");
return head;
}
public boolean isEmpty() {
if (head.next == head) {
return true;
} else {
return false;
}
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public ListNode getHead() {
return head;
}
public void setHead(ListNode head) {
this.head = head;
}
}