forked from gouthampradhan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PaliandromeList.java
86 lines (76 loc) · 2.09 KB
/
PaliandromeList.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package linked_list;
/**
* Created by gouthamvidyapradhan on 25/02/2017.
* Given a singly linked list, determine if it is a palindrome.
* <p>
* Follow up:
* Could you do it in O(n) time and O(1) space?
*/
public class PaliandromeList {
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
ListNode headNode;
/**
* Main method
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
ListNode node1 = new ListNode(1);
//ListNode node2 = new ListNode(2);
//ListNode node3 = new ListNode(3);
//ListNode node4 = new ListNode(3);
//ListNode node5 = new ListNode(2);
//ListNode node6 = new ListNode(1);
//node1.next = node2;
//node2.next = node3;
//node3.next = node5;
//node4.next = node5;
//node5.next = node6;
System.out.println(new PaliandromeList().isPalindrome(node1));
}
public boolean isPalindrome(ListNode head) {
int length = 0, count = 0;
if (head == null) return true;
ListNode temp = head;
while (temp != null) {
temp = temp.next;
length++;
}
if (length == 1) return true;
int halfLen = length / 2;
temp = head;
while (count < halfLen - 1) {
temp = temp.next;
count++;
}
ListNode newHead = temp.next;
temp.next = null;
reverse(newHead);
ListNode first = head, second = headNode;
for (int i = 0; i < halfLen; i++) {
if (first.val != second.val)
return false;
first = first.next;
second = second.next;
}
return true;
}
private ListNode reverse(ListNode node) {
if (node.next == null) {
headNode = node;
return node;
}
ListNode prev = reverse(node.next);
node.next = null;
prev.next = node;
return node;
}
}