-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList.java
More file actions
77 lines (76 loc) · 2.06 KB
/
LinkedList.java
File metadata and controls
77 lines (76 loc) · 2.06 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
import java.util.*;
public class LinkedList{
private static class Node{
int data;
Node nextNode;
Node(int data){
this.data=data;
nextNode=null;
}
}
private static Node head=null;
public static Node insertNode(int data,Node head){
if(head==null){
return new Node(data);
}else{
Node temNode=new Node(data);
temNode.nextNode=head;
head=temNode;
return head;
}
}
public static void printLL(){
Node temp=head;
while(temp!=null){
System.out.print(temp.data+" ");
temp=temp.nextNode;
}
System.out.println();
}
public static Node reverseList(Node head){
if(head==null){
return null;
}else{
Node head2=null;
while(head!=null){
head2=insertNode(head.data,head2);
head=head.nextNode;
}
return head2;
}
}
public static int isPalindrome(Node head){
int flag=1;
Node slow=head,fast=head.nextNode;
while(fast!=null && fast.nextNode!=null){
slow=slow.nextNode;
fast=fast.nextNode.nextNode;
}
slow.nextNode=reverseList(slow.nextNode);
Node a=head,b=slow.nextNode;
while(a!=null && b!=null){
if(a.data!=b.data){
flag=0;
break;
}
a=a.nextNode;
b=b.nextNode;
}
slow.nextNode=reverseList(slow.nextNode);
return flag;
}
public static void main(String[] args) {
int q;
Scanner sc=new Scanner(System.in);
q=sc.nextInt();
while(q-->0){
int n=sc.nextInt();
for(int i=0;i<n;i++){
int data=sc.nextInt();
head=insertNode(data, head);
}
System.out.println(isPalindrome(head));
}
sc.close();
}
}