-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprblm234.java
More file actions
53 lines (48 loc) · 1.4 KB
/
prblm234.java
File metadata and controls
53 lines (48 loc) · 1.4 KB
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
import java.util.*;
public class prblm234 {
public static void main(String[] args) {
ListNode l1 = new ListNode(1);
ListNode l2 = new ListNode(2);
ListNode l3 = new ListNode(2);
ListNode l4 = new ListNode(1);
l1.next = l2;
l2.next = l3;
l3.next = l4;
ListNode head = l1;
printList(head);
System.out.println(isPalindromeUsingString(head));
}
public static boolean isPalindrome(ListNode head) {
ListNode curr = head;
Stack<Integer> stack = new Stack<>();
while (curr != null) {
stack.push(curr.val);
curr = curr.next;
}
curr = head;
while (curr != null) {
if (curr.val != stack.pop()) {
return false;
}
curr = curr.next;
}
return true;
}
public static boolean isPalindromeUsingString(ListNode head) {
ListNode curr = head;
StringBuilder str = new StringBuilder();
while (curr != null) {
str.append(curr.val);
curr = curr.next;
}
return str.toString().equals(str.reverse().toString());
}
public static void printList(ListNode head){
ListNode curr = head;
while(curr != null){
System.out.print(curr.val + " ");
curr = curr.next;
}
System.out.println();
}
}