Program Stack Palindrome
Berikut ini merupakan contoh program palindrome dengan stack menggunakan bahasa pemrograman java:
Source Code
1. Class cElement
public class cElement {
private String name;
private char chars;
cElement next;
cElement (String n){
name = n;
System.out.println("Object "+n+" created...");
}
cElement (char c){
chars = c;
}
public String getName() {
return name;
}
public char getChars() {
return chars;
}
}
2. Class cStack
public class cStack {
cElement top, bottom;
String word;
int total;
cStack(){
top = bottom = null;
total = 0;
System.out.println("Object stack has been created...");
}
public void push (cElement newest) {
if(top == null) {
top = bottom = newest;
}
else {
newest.next = top;
top = newest;
}
System.out.println("Push OK...");
}
public cElement pop() {
if(top == null) {
System.out.println("Stack empty!");
return null;
}
else if(top.next == null) {
cElement t = top;
top = bottom = null;
System.out.println("Pop OK...");
return t;
}
else {
cElement t = top;
top = top.next;
t.next = null;
System.out.println("Pop OK...");
return t;
}
}
public void palindrome(cElement pl) {
word = pl.getName();
boolean palindrome = false;
for (int i = 0; i < word.length(); i++) {
cElement wd = new cElement(word.charAt(i));
push(wd);
}
for (int i = 0; i < word.length(); i++) {
if(pop().getChars() == word.charAt(i)) {
System.out.println("Same");
palindrome = true;
}
else {
System.out.println("Not same");
palindrome = false;
break;
}
}
if(palindrome == true) {
System.out.println("This word is palindrome");
}
else {
System.out.println("This word isn't palindrome");
}
}
}
3. Class appStackPalindrome
import java.util.Scanner;
public class appStackPalindrome {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
cStack stack = new cStack();
int select = 0;
do {
System.out.println("\nMENU STACK PALINDROME");
System.out.println("1. Palindrome");
System.out.println("2. Exit");
System.out.print("Select = ");
select = sc.nextInt();
switch(select) {
case 1:
System.out.print("Input word = ");
String wd = sc.next();
cElement w = new cElement(wd);
stack.palindrome(w);
System.out.println("");
break;
case 2:
System.out.println("Thank you...");
break;
}
} while(select != 2);
}
}

Comments