-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindromeLinkedList.java
More file actions
62 lines (50 loc) · 1.47 KB
/
PalindromeLinkedList.java
File metadata and controls
62 lines (50 loc) · 1.47 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
54
55
56
57
58
59
60
61
62
package Leetcode;
class PalindromeLinkedList
{
public boolean isPalindrome(ListNode head) {
ListNode fast = head;
ListNode slow = head;
if(fast==null || fast.next==null)
return true;
if(fast.next.next==null && fast.val==fast.next.val)
return true;
while(fast.next!=null && fast.next.next!=null)
{
fast = fast.next.next;
slow = slow.next;
}
ListNode reversedList = reverseList(slow.next);
while(reversedList!=null)
{
if(head.val!=reversedList.val)
return false;
head = head.next;
reversedList = reversedList.next;
}
return true;
}
public ListNode reverseList(ListNode head)
{
if(head==null)
return head;
ListNode c1= head;
ListNode temp = null;
while(c1!=null)
{
ListNode c2= c1.next;
c1.next = temp;
temp = c1;
c1=c2;
}
return temp;
}
public static void main( String[] args )
{
PalindromeLinkedList obj = new PalindromeLinkedList();
ListNode n1= new ListNode( 1 );
n1.next = new ListNode(1);
n1.next.next = new ListNode(2);
n1.next.next.next = new ListNode(1);
System.out.println( obj.isPalindrome( n1 ) );
}
}