Kod dibawah adalah dalam Java.
Node class
public class Node {
int data;
Node nextNode;
// CONSTRUCTOR
public Node(int data) {
this.data = data;
this.nextNode = null;
}
}
Linked List class
public class LinkedList {
Node head;
Node tail;
// CONSTRUCTOR
public LinkedList() {
this.head = null;
this.tail = null;
}
// METHOD
// isEmpty()
public boolean isEmpty() {
if (this.head == null) {
return true;
}
return false;
}
// display()
// traverse()
public void display() {
if (isEmpty()) {
System.out.println("It's empty");
}
else {
Node current = this.head;
while (current != null) {
System.out.println(current.data);
current = current.nextNode;
}
}
}
// insertAtFront()
public void insertAtFront(int newData) {
Node newNode = new Node(newData);
if (isEmpty()) {
this.head = newNode;
this.tail = newNode;
}
else {
newNode.nextNode = this.head;
this.head = newNode;
}
}
// insertAtBack()
public void insertAtBack(int newData) {
Node newNode = new Node(newData);
if (isEmpty()) {
this.head = newNode;
this.tail = newNode;
}
else {
this.tail.nextNode = newNode;
this.tail = newNode;
}
}
// removeFront()
public int removeFront() {
int removeItem = -999;
if (isEmpty()) {
return removeItem; // -999
}
removeItem = this.head.data;
if (this.head == this.tail) {
this.head = null;
this.tail = null;
}
else {
this.head = this.head.nextNode;
}
return removeItem;
}
// removeBack()
public int removeBack() {
int removeItem = -999;
if (isEmpty()) {
return removeItem;
}
removeItem = this.tail.data;
if (this.head == this.tail) {
this.head = null;
this.tail = null;
}
else {
Node current = this.head;
while (current.nextNode != this.tail) {
current = current.nextNode;
}
this.tail = current;
this.tail.nextNode = null;
}
return removeItem;
}
// getIndex() / findData()
public int getIndex(int index) {
int foundItem = -999;
if (isEmpty()) {
return foundItem;
}
else {
int count = 0;
Node current = this.head;
while (current != null && count <= index) {
if (count == index) {
foundItem = current.data;
}
current = current.nextNode;
count++;
}
return foundItem;
}
}
// removeIndex()
public int removeIndex(int index) {
int removeItem = -999;
if (isEmpty()) {
return removeItem;
}
if (index == 0) {
return removeFront();
}
else {
int count = 0;
Node current = this.head;
Node prev = null;
while (current != null && count <= index) {
if (index == count) {
removeItem = current.data;
prev.nextNode = current.nextNode;
current.nextNode = null;
}
prev = current;
current = current.nextNode;
count++;
}
return removeItem;
}
}
}