Skip to content

Create Palindrome Linked List #2362

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
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
48 changes: 48 additions & 0 deletions DataStructures/Lists/Palindrome Linked List.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
//Palindrome Linked List

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
}
slow = reverse(slow);
fast = head;

while(slow !=null){
if(slow.val != fast.val){
return false;
}
slow = slow.next;
fast = fast.next;

}
return true;
}

public ListNode reverse(ListNode head){
ListNode prev = null;
while(head !=null){
//null 3->2->1
ListNode next = head.next;
head.next = prev;
// null<-3 2->1
prev = head;
head = next;

}
return prev;
}
}