Class Node
public class Node{
int data;
Node next;
Node prev;
public Node(int data){
this.data = data;
}
public void tampil(){
System.out.print("("+data+")");
}
}
Class DoublyLinkedList
public class DoubleLinkedList{
Node first;
Node last;
public DoubleLinkedList(){
first = null;
last = null;
}
public boolean isEmpty(){
return (first == null);
}
public void insertFirst(int data){
Node node = new Node(data);
if(isEmpty()){
last = node;
}
else{
first.prev = node;
}
node.next = first;
first = node;
}
public void insertLast(int data){
Node node = new Node(data);
if(isEmpty())
first = node;
else{
last.next = node;
node.prev = last;
}
last = node;
}
public Node deleteFirst(){
Node temp = first;
if(first.next == null)
last = null;
else
first.next.prev = null;
first = first.next;
return temp;
}
public Node deleteLast(){
Node temp = last;
if (first.next == null)
first = null;
else
last.prev.next = null;
last = last.prev;
return temp;
}
public boolean insertAfter(int key, int data){
Node current = first;
while(current.data != key){
current = current.next;
if(current == null)
return false;
}
Node node = new Node(data);
if (current==last){
node.next = null;
last = node;
}
else{
node.next = current.next;
current.next.prev = node;
}
node.prev = current;
current.next = node;
return true;
}
public Node deleteKey(int key){
Node current = first;
while(current.data != key){
current = current.next;
if(current == null)
return null;
}
if(current == first)
first = current.next;
else
current.prev.next = current.prev;
return current;
}
public void displayForward(){
System.out.print("List | First -> Last : ");
Node current = first;
while(current != null){
current.tampil();
current = current.next;
}
System.out.println("");
}
public void displayBackward(){
System.out.print("List | Last -> First : ");
Node current = last;
while(current != null){
current.tampil();
current = current.prev;
}
System.out.println("");
}
}
Class APP
public class APP{
public static void main(String[] args){
DoubleLinkedList list = new DoubleLinkedList();
list.insertFirst(10);
list.insertFirst(15);
list.insertFirst(20);
list.insertLast(30);
list.insertLast(35);
list.insertLast(40);
list.displayForward();
list.displayBackward();
list.deleteFirst();
list.deleteLast();
list.deleteKey(15);
list.displayForward();
list.insertAfter(10, 90);
list.insertAfter(30, 95);
list.displayForward();
}
}
>>> Link Github <<<
Tidak ada komentar:
Posting Komentar