-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathpalindrome_linkedlist.java
74 lines (61 loc) · 1.94 KB
/
palindrome_linkedlist.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
package Linkedlist;
public class palindrome_linkedlist {
Node head;
static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
public Node reverse(Node head)
{
if(head==null||head.next==null)
{return head;}
Node new_head=reverse(head.next);
Node headnext=head.next;
headnext.next=head;
head.next=null;
return new_head;
}
public Node middle(Node head)
{
Node slow=head;
Node fast=head;
while(fast!=null&&fast.next!=null)
{
slow=slow.next;
fast=fast.next.next;
}
return slow;
}
public boolean ispalindrome(Node head)
{
if(head==null||head.next==null)
{
return true;
}
Node middle_node=middle(head);
Node first_pointer=head;
Node last_pointer=reverse(middle_node);
while(last_pointer!=null) {
if (first_pointer.data != last_pointer.data) {
return false;
}
first_pointer = first_pointer.next;
last_pointer = last_pointer.next;
}
return true;
}
public static void main(String args[])
{
palindrome_linkedlist ll=new palindrome_linkedlist();
ll.head = new palindrome_linkedlist.Node(1);
ll.head.next = new palindrome_linkedlist.Node(3);
ll.head.next.next = new palindrome_linkedlist.Node(2);
ll.head.next.next.next = new palindrome_linkedlist.Node(4);
ll.head.next.next.next.next = new palindrome_linkedlist.Node(1);
System.out.println(ll.ispalindrome(ll.head));
}
}