Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions palindrome-linked-list.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
class Solution {
public boolean isPalindrome(ListNode head) {

//if linkedList have only one node or null return
if(head==null || head.next==null) return true;

//Finding the first middle element in a linkedList.
ListNode slow=head;
ListNode fast=head;

while(fast.next!=null && fast.next.next!=null){
fast=fast.next.next;
slow=slow.next;
}

//getting the reverse part of linkedList and connecting it.
slow.next=reverseLinkedList(slow.next);
slow=slow.next;

//checking is palindrome or not.
ListNode dummy=head;
while(slow!=null){
if(dummy.val!=slow.val)
return false;
slow=slow.next;
dummy=dummy.next;
}
return true;
}

//reversing LinkedList from middle Next.
ListNode reverseLinkedList(ListNode head) {
ListNode pre=null;
ListNode next=null;
while(head!=null){
next=head.next;
head.next=pre;
pre=head;
head=next;
}
return pre;
}
}