diff --git a/Program's_Contributed_By_Contributors/Java_Programs/Data_structure/PalindromeLL.java b/Program's_Contributed_By_Contributors/Java_Programs/Data_structure/PalindromeLL.java new file mode 100644 index 000000000..e638c8123 --- /dev/null +++ b/Program's_Contributed_By_Contributors/Java_Programs/Data_structure/PalindromeLL.java @@ -0,0 +1,127 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +class LinkedListNode { + T data; + LinkedListNode next; + + public LinkedListNode(T data) { + this.data = data; + } +} + +class Solution { + + public static LinkedListNode middle(LinkedListNode head){ + LinkedListNode fast=head,slow=head; + + while(fast!=null && fast.next!=null){ + slow=slow.next; + fast=fast.next.next; + } + return slow; + } + + public static LinkedListNode reverseI(LinkedListNode head){ + + + LinkedListNodecurr=head,prev=null; + while(curr!=null){ + LinkedListNode temp=curr.next; + curr.next=prev; + prev=curr; + curr=temp; + } + + return prev; + + } + + public static LinkedListNode reverseR(LinkedListNode head){ + if(head==null || head.next==null){ + return head; + } + LinkedListNode newHead=reverseR(head.next); + LinkedListNode headNext=head.next; + headNext.next=head; + head.next=null; + return newHead; + + + } + + public static boolean isPalindrome(LinkedListNode head) { + + if(head==null || head.next==null){ + return true; + } + LinkedListNode mid=middle(head); + LinkedListNode last=reverseR(mid); + LinkedListNode curr=head; + + while(curr!=null && last!=null){ + if(!(curr.data.equals(last.data))){ + return false; + } + curr=curr.next; + last=last.next; + } + + return true; + } + +} + +public class PalindromeLL { + + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + public static LinkedListNode takeInput() throws IOException { + LinkedListNode head = null, tail = null; + + String[] datas = br.readLine().trim().split("\\s"); + + int i = 0; + while(i < datas.length && !datas[i].equals("-1")) { + int data = Integer.parseInt(datas[i]); + LinkedListNode newNode = new LinkedListNode(data); + if(head == null) { + head = newNode; + tail = newNode; + } + else { + tail.next = newNode; + tail = newNode; + } + i += 1; + } + + return head; + } + + public static void print(LinkedListNode head){ + while(head != null) { + System.out.print(head.data + " "); + head = head.next; + } + + System.out.println(); + } + + public static void main(String[] args) throws NumberFormatException, IOException { + int t = Integer.parseInt(br.readLine().trim()); + + while (t > 0) { + + LinkedListNode head = takeInput(); + + boolean ans = Solution.isPalindrome(head); + System.out.println(ans); + + t -= 1; + + } + + } +}