STACK ( WITH SINGLE LINKED LIST )
NAMA : ELI NURHAYATI
NPM : 20082010115
SOAL
Buatlah
aplikasi Stack dengan menggunakan single linked list yang memiliki menu push,
pop, cetak, dan exit. Data yang disimpan adalah nama-nama barang. Uji cobakan
scenario : push, push, cetak, pop, pop, pop, cetak, push, cetak.
CLASS –
CLASS
Class cSimpulStack
package stack; public class cSimpulStack {
String name;
//Pointer
cSimpulStack next;
//Constructor
cSimpulStack(String nm){ name=nm; System.out.println(">>
Item "+nm+" created... <<");
}
//Method Getter
public String getName(){ return name;
} } |
Class
cStack
package stack; public class cStack {
cSimpulStack head, tail;
int jumlah;
//Constructor
cStack(){ head=tail=null; jumlah=0; System.out.println(">>
Object Stack Created... <<");
}
//Method Operasi Push
public void push(cSimpulStack neww){ if(head==null){ //Stack masih kosong head=tail=neww; }else{ //Stack sudah terisi neww.next=head; head=neww; }
}
//Method Operasi Pop
public cSimpulStack pop(){ cSimpulStack a=head; if(head==null){ //Stack kosong return null; }else if(head.next==null){ //Isi stack sisa 1 head=tail=null; System.out.println(">>
POP Success... <<"); return a; }else{ //Isi stack >1 head=head.next; a.next=null; System.out.println(">>
POP Success... <<"); return a; }
}
//Method Operasi Print
public void print(){
System.out.println("================="); System.out.println(" ISI STACK ");
System.out.println("================="); for(cSimpulStack a=head; a!=null;
a=a.next){
System.out.println("| "+a.getName()+"\t|"); }
} } |
Class
apkStack
package stack; import java.util.Scanner; public class apkStack {
public static void main(String[] args) { Scanner s = new Scanner(System.in); cStack st = new cStack(); int pilih=0; do{
System.out.println("\n================"); System.out.println(" MENU STACK ");
System.out.println("================"); System.out.println("1. Push
Stack\n2. Pop Stack\n3. Print Stack\n4. Exit"); System.out.print("Input
Pilihan Anda : "); pilih = s.nextInt(); switch(pilih){ case 1 :
System.out.print("Input Nama Barang : "); String brg = s.next(); cSimpulStack a = new
cSimpulStack(brg); st.push(a); break; case 2 : cSimpulStack b = st.pop(); if(b==null){
System.out.println(">> Oops Stack is empty...
<<"); }else{
System.out.println(">> "+b.getName()+" out...
<<"); } break; case 3 :
st.print(); break; case 4: System.out.println("
>>> THANK YOU <<<"); } }while(pilih!=4);
}
} |
SCREENSHOT
RUNNING PROGRAM
Push Stack
Print Stack
Pop Stack
Print Stack
Push Stack
Print Stack
Exit Stack
*Klik
gambar untuk gambar yang lebih jelas
**Saran dan
kritik anda sangat berguna untuk blog ini kedepannya
***Thank You 😊😊😊
Komentar
Posting Komentar