Stack Palindrom - Sulthan Atha Muhammad (21082010126)
Class cNode
package Stack;
public class cNode {
private char huruf;
cNode next, prev;
cNode(char hrf){
huruf=hrf;
}
public char getHuruf(){
return huruf;
}
}
Class cStack
package Stack;
public class cStack {
cNode atas , bawah;
int jumlah;
cStack(){
atas=bawah=null;
jumlah=0;
}
public void push(cNode baru){
if(atas==null){
atas=bawah=baru;
}else{
baru.next=atas;
atas.prev=baru;
atas=baru;
}
}
public cNode pop(){
if(atas==null){
System.out.println("Stack Kosong");
return null;
}else if(atas.next == null){
cNode temp = atas;
atas = bawah = null;
temp.next = null;
temp.prev = null;
return temp;
}else{
cNode temp = atas;
atas = atas.next;
atas.prev = null;
temp.next = null;
temp.prev = null;
return temp;
}
}
public void reset(){
for (cNode temp = atas; temp !=null; temp = temp.next){
if(temp==null){
System.out.println("Kosong");
}
pop();
}
}
public void print(){
for(cNode temp = atas; temp !=null; temp = temp.next){
System.out.println(temp.getHuruf());
}
}
public String cekAtas(){
String hasil="";
for(cNode temp = atas; temp != null; temp = temp.next){
String t = Character.toString(temp.getHuruf());
hasil+=t;
}
System.out.println("Dari Atas : "+hasil);
return hasil;
}
public String cekBawah(){
String hasil="";
for (cNode temp = bawah; temp != null; temp = temp.prev) {
String t = Character.toString(temp.getHuruf());
hasil += t;
}
System.out.println("Dari Bawah: "+hasil);
return hasil;
}
}
Class appStackPalindrom
package Stack;
import java.util.Scanner;
public class appStackPalindrom {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
cStack tumpuk = new cStack();
String kata;
int pilih = 0;
do {
System.out.println("APLIKASI STACK PALINDROM");
System.out.println("1. Cek Palindrom");
System.out.println("2. Selesai");
System.out.print("Pilih : ");
pilih = sc.nextInt();
switch(pilih){
case 1 :
System.out.println("CEK PALINDROM");
System.out.print("Masukkan Kata : ");
kata = sc.next();
for (int i = 0; i < kata.length(); i++) {
char cr = kata.charAt(i);
cNode temp = new cNode(cr);
tumpuk.push(temp);
}
String atas = tumpuk.cekAtas();
String bawah = tumpuk.cekBawah();
if (atas.equalsIgnoreCase(bawah)) {
System.out.print("Tampil Stack : ");
tumpuk.print();
System.out.println("-> Merupakan PALINDROM");
}else{
System.out.print("Tampil Stack : ");
tumpuk.print();
System.out.println("-> Bukan PALINDROM");
}
for (int i = 0; i < atas.length(); i++) {
tumpuk.pop();
}
break;
case 2 :
System.out.println("TERIMA KASIH");
break;
}
} while (pilih!=2);
}
}
Comments
Post a Comment