POLINDROM
NAMA: SYURAINI NOOR CHAMSYAH
NPM: 22082010033
Souce Code
package polindrom;
import java.util.Scanner;
class Node {
char data;
Node next;
public Node(char data) {
this.data = data;
this.next = null;
}
}
class Stack {
private Node top;
public Stack() {
this.top = null;
}
public void push(char data) {
Node newNode = new Node(data);
if (isEmpty()) {
top = newNode;
} else {
newNode.next = top;
top = newNode;
}
}
public char pop() {
if (isEmpty()) {
System.out.println("Stack is empty.");
return '\0';
} else {
char data = top.data;
top = top.next;
return data;
}
}
public char peek() {
if (isEmpty()) {
System.out.println("Stack is empty.");
return '\0';
} else {
return top.data;
}
}
public boolean isEmpty() {
return top == null;
}
}
public class Polindrom {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Masukkan sebuah kata: ");
String kata = input.nextLine();
if (isPolindrome(kata)) {
System.out.println("Kata \"" + kata + "\" adalah palindrom.");
} else {
System.out.println("Kata \"" + kata + "\" bukan palindrom.");
}
}
public static boolean isPolindrome(String kata) {
Stack stack = new Stack();
int panjang = kata.length();
for (int i = 0; i < panjang; i++) {
stack.push(kata.charAt(i));
}
for (int i = 0; i < panjang; i++) {
if (kata.charAt(i) != stack.pop()) {
return false;
}
}
return true;
}
}
Screenshoot Run
Komentar
Posting Komentar