Latihan Stack 22082010015 Arsa Cahaya Pradipta
Source code:
package latihan_mandiri;
public class cNode {
String data;
cNode next;
public cNode(String d){
data = d;
}
}
package latihan_mandiri;
public class cStack {
private cNode top;
public boolean isEmpty() {
return top == null;
}
public void push(String data) {
cNode newNode = new cNode(data);
newNode.next = top;
top = newNode;
}
public String pop() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty");
}
String data = top.data;
top = top.next;
return data;
}
public String peek() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty");
}
return top.data;
}
}
package latihan_mandiri;
import java.util.Scanner;
public class appStack {
public static boolean isPalindrome(String word) {
cStack stack = new cStack();
int length = word.length();
for (int i = 0; i < length; i++) {
stack.push(Character.toString(word.charAt(i)));
}
for (int i = 0; i < length; i++) {
if (!word.substring(i, i + 1).equals(stack.pop())) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int pilih = 0;
do {
System.out.println(" LATIHAN INDIVIDU STACK ");
System.out.println("ARSA CAHAYA PRADIPTA \t 22082010015");
System.out.println("======================================");
System.out.println("1. Palindrom\n2. Exit");
System.out.print("Pilih: ");
pilih = s.nextInt();
if(pilih == 1) {
System.out.print("Input kata: ");
String word = s.next();
if (isPalindrome(word)) {
System.out.println("Palindrom");
} else {
System.out.println("Bukan Palindrom");
}
System.out.println("");
} else {
System.out.println("Terima kasih...");
}
} while(pilih != 2);
}
}
Output:
Comments
Post a Comment