forked from DaffaTakarai/HacktoberFest2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPalindromeLinkedList.java
60 lines (59 loc) · 1.37 KB
/
PalindromeLinkedList.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* PalindromeLinkedList
*/
import java.util.*;
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
Node head;
public void add(int val) {
Node node = new Node(val);
if(head==null) {
head = node;
}
else {
node.next = head;
head = node;
}
}
public void display() {
Node temp = head;
while(temp!=null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
public boolean palindrome() {
if(head==null)
return true;
StringBuilder sb = new StringBuilder("");
Node temp = head;
while(temp!=null) {
sb.append(temp.data);
temp = temp.next;
}
String org = sb.toString();
String rev = sb.reverse().toString();
System.out.println(org + " " + rev);
return rev.equals(org);
}
}
public class PalindromeLinkedList {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
ll.add(11);
ll.add(22);
ll.add(33);
ll.add(44);
ll.add(55);
// ll.display();
System.out.println("The linked list is a palindrome:- " + ll.palindrome());
}
}