DEV Community

ashutosh049
ashutosh049

Posted on • Updated on

check if Linked List is palindrome or not

Alt Text

Approach

  1. Find the middle Node
  2. Reverse the latter half of list
  3. Compare each node of the original list to reversed list.
    • Note: the list returned after reversing, breaks the original list into 2 parts, we return the prev which is reversed

Node Def

 class ListNode {
      public int val;
      public ListNode next;
      ListNode(int x) { val = x; next = null; }
  }

Enter fullscreen mode Exit fullscreen mode

Runner class

public class LinkedListPalindrome{
    public int isPalindrome(ListNode root) {

        // If no Node, false always
        if (root == null)
            return 0;

        // If single Node only, true always
        if (root.next == null)
            return 1;

        ListNode curr = root;

        //1. Find the middle Node
        ListNode midNode = findMidNode(curr);
        //2. Reverse the latter half of list
        ListNode revNode = reverseNodeList(midNode);
        //3. Compare each node 
        curr = root;
        while(curr != null && revNode != null){
            if(curr.val != revNode.val){
                return 0;
            }
            curr = curr.next;
            revNode = revNode.next;
        }
        return 1;
    }
Enter fullscreen mode Exit fullscreen mode

find the middle node

  1. If list size is even , middle Node will be len/2 th Node
  2. If list size is odd, middle Node will be len/2 th Node(floor Node)
    /**
     * Use 2 pointer approach
     * fast pointer nad slow pointer
     */
    private ListNode findMidNode(ListNode root){
        ListNode sp = root;
        ListNode fp = root;
        while(fp.next != null && fp.next.next !=null){
            fp = fp.next.next;
            sp = sp.next;
        }
        return sp;
    }
Enter fullscreen mode Exit fullscreen mode
    private ListNode reverseNodeList(ListNode root){
        ListNode curr = root;
        ListNode prev = null;
        ListNode next = null;

        while(curr != null ){
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)