|
| 1 | +package in.knowledgegate.dsa.linkedlist; |
| 2 | + |
| 3 | +import in.knowledgegate.dsa.ListNode; |
| 4 | + |
| 5 | +/** |
| 6 | + * Given the head of a singly linked list, |
| 7 | + * return true if it is a palindrome. |
| 8 | + * |
| 9 | + * Example 1: |
| 10 | + * Input: head = [1,2,2,1] |
| 11 | + * Output: true |
| 12 | + * |
| 13 | + * Example 2: |
| 14 | + * Input: head = [1,2] |
| 15 | + * Output: false |
| 16 | + * |
| 17 | + * Constraints: |
| 18 | + * The number of nodes in the list is in the range [1, 105]. |
| 19 | + * 0 <= Node.val <= 9 |
| 20 | + * |
| 21 | + * Follow up: Could you do it in O(n) time and O(1) space? |
| 22 | + */ |
| 23 | +public class PalindromeLinkedList { |
| 24 | + public static void main(String[] args) { |
| 25 | + PalindromeLinkedList checker = |
| 26 | + new PalindromeLinkedList(); |
| 27 | + ListNode fourth = new ListNode(1); |
| 28 | + ListNode third = new ListNode(2, fourth); |
| 29 | + ListNode second = new ListNode(3, third); |
| 30 | + ListNode first = new ListNode(1, second); |
| 31 | + System.out.println("Palindrome status: " |
| 32 | + + checker.isPalindrome(first)); |
| 33 | + } |
| 34 | + |
| 35 | + public boolean isPalindrome(ListNode head) { |
| 36 | + ListNode slow = head, fast = head; |
| 37 | + while (fast != null && fast.next != null) { |
| 38 | + slow = slow.next; |
| 39 | + fast = fast.next.next; |
| 40 | + } |
| 41 | + |
| 42 | + ListNode reversed = reverse(slow); |
| 43 | + while(head != null && reversed != null) { |
| 44 | + if (head.val != reversed.val) return false; |
| 45 | + head = head.next; |
| 46 | + reversed = reversed.next; |
| 47 | + } |
| 48 | + return true; |
| 49 | + } |
| 50 | + |
| 51 | + private ListNode reverse(ListNode node) { |
| 52 | + ListNode prev = null; |
| 53 | + while (node != null) { |
| 54 | + ListNode temp = node.next; |
| 55 | + node.next = prev; |
| 56 | + prev = node; |
| 57 | + node = temp; |
| 58 | + } |
| 59 | + return prev; |
| 60 | + } |
| 61 | +} |
0 commit comments