-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuestion234.java
More file actions
113 lines (99 loc) · 1.94 KB
/
Copy pathQuestion234.java
File metadata and controls
113 lines (99 loc) · 1.94 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/*
Author: Ananthanarayanan R
Section: Algorithms
Question: 234
*/
/*
TestCases-
*/
public class Question234
{
/*
public static boolean isPalindrome(ListNode head)
{
if(head.next==null)
return true;
ListNode temp = head;
int length = 0;
while(temp!=null)
{
length++;
temp = temp.next;
}
System.out.println(length);
int diff = length - 1;
for(int i = 0;i<length/2;i++)
{
temp = head;
for(int j = 1;j<=diff;j++)
temp = temp.next;
if(head.val != temp.val)
return false;
head = head.next;
diff-=2;
}
return true;
}
*/
public static boolean isPalindrome(ListNode head)
{
if(head==null)
return false;
if(head.next==null)
return true;
ListNode temp = head;
int length = 0;
while(temp!=null)
{
length++;
temp = temp.next;
}
int index = 0;
temp = head;
ListNode list2 = head;
while(index<length/2-1)
{
head = head.next;
index++;
}
if(length%2==0)
list2 = head.next;
else
list2 = head.next.next;
head.next = null;
list2 = reverse(list2);
LinkedList.displayLinkedList(temp);
LinkedList.displayLinkedList(list2);
for(int i = 0;i<length/2;i++)
{
if(temp.val!=list2.val)
return false;
temp = temp.next;
list2 = list2.next;
}
return true;
}
public static ListNode reverse(ListNode head)
{
if(head == null || head.next==null)
return head;
ListNode p1 = null, p2 = head;
while(head!=null)
{
p2 = head.next;
head.next = p1;
p1 = head;
head = p2;
}
return p1;
}
public static void main(String[] args)
{
System.out.println("Main Method starts");
ListNode head1 = LinkedList.createLinkedList(11,"unsorted");
LinkedList.displayLinkedList(head1);
System.out.println(isPalindrome(head1));
//ListNode reverse = reverse(head1);
//LinkedList.displayLinkedList(reverse);
}
}