publicclassLinkedListPalindrome{publicintisPalindrome(ListNoderoot){// If no Node, false alwaysif(root==null)return0;// If single Node only, true alwaysif(root.next==null)return1;ListNodecurr=root;//1. Find the middle NodeListNodemidNode=findMidNode(curr);//2. Reverse the latter half of listListNoderevNode=reverseNodeList(midNode);//3. Compare each node curr=root;while(curr!=null&&revNode!=null){if(curr.val!=revNode.val){return0;}curr=curr.next;revNode=revNode.next;}return1;}
find the middle node
If list size is even , middle Node will be len/2 th Node
If list size is odd, middle Node will be len/2 th Node(floor Node)
/**
* Use 2 pointer approach
* fast pointer nad slow pointer
*/privateListNodefindMidNode(ListNoderoot){ListNodesp=root;ListNodefp=root;while(fp.next!=null&&fp.next.next!=null){fp=fp.next.next;sp=sp.next;}returnsp;}
Top comments (0)