import java.util.Scanner;
class LimkListApp{
public static void main (String[] args){
Scanner in=new Scanner (System.in);
LinkList List=new LinkList();
int td,n,pilih;
char Lagi;
Node hapus;
do {
System.out.println ("Pilihan data: ");
System.out.println ("1. Tambah Depan ");
System.out.println ("2. Tambah Belakang ");
System.out.println ("1. Hapus Depan ");
System.out.println ("2. Hapus Belakang");
System.out.print ("Pilih: ");
pilih = in.nextInt();
switch (pilih) {
case 1 : System.out.print ("Masukkan untuk menambah data: ");
td=in.nextInt();
List.tambahDepan(td);
break;
case 2 : System.out.print ("Masukkan untuk menambah data: ");
td=in.nextInt();
List.tambahBelakang(td);
break;
case 3 : hapus=List.hapusDepan();
if(hapus!=null)
System.out.println(hapus.data + " terhapus .");
break;
case 4 : hapus=List.hapusBelakang();
if(hapus!=null)
System.out.println(hapus.data + " terhapus .");
break;
default : System.out.println ("Pilihan tidak ada");
}
List.displayList();
System.out.print ("Lagi? ");
Lagi = in.next().charAt(0);
}
while (Lagi == 'y' || Lagi == 'Y');
}
}
---------------------------------------------------------------------------------------------------------------
class LinkList{
private Node head, tail;
public LinkList(){
head=null;
}
public void tambahDepan(int d){
Node baru=new Node(d);
if (head==null){
head=baru;
tail=baru;
}
else{
baru.next=head;
head=baru;
}
}
public void tambahBelakang(int d){
Node baru=new Node(d);
if(head==null){
head=baru;
tail=baru;
}
else{
tail.next=baru;
tail=baru;
}
}
public Node hapusDepan(){
if(head!=null){
Node temp=head;
head=head.next;
temp.next=null;
return temp;
}
else{
System.out.println("list kosong");
return null;
}
}
public Node hapusBelakang(){
if(head!=null){
Node bantu, temp;
if(head.next==null){
temp = head;
head = tail = null;
}
else{
bantu=head;
while(bantu.next!=tail);{
bantu=bantu.next;
}
temp=tail;
tail=bantu;
tail.next=null;
}
return temp;
}
else{
System.out.println("List Kosong. ");
return null;
}
}
public void displayList(){
if(head!=null){
Node bantu=head;
System.out.println("Data Dalam List :");
while(bantu!=null){
System.out.print(bantu.data + " ");
bantu=bantu.next;
}
System.out.println("");
}
else
System.out.println("List Kosong.");
}
}
-------------------------------------------------------------------------------------------------------------
class Node{
public int data;
public Node next;
public Node(int d){
data=d;
next=null;
}
}
Langganan:
Posting Komentar (Atom)
0 komentar:
Posting Komentar