Given a singly linked list, determine if it is a palindrome.
The problem is to judge whether a linked list is not a palindrome list.
Idea one: Invert the list and then compare node values from scratch, time complexity O (n), spatial complexity O (n)
Idea two: Use runner pointer. Many of the topics can be solved using this method. Runner Pointer and recursion are the two most common ways to solve a list problem.
Defines two pointers, slow runner and fast runner,fast move to the tail of the list at twice times the speed of the slow. If there is an odd number of nodes: When fast reaches the end of the list, the slow happens to reach the middle of the list. If there is an even number of nodes: When fast is null for the first time, slow completes the access of half the nodes exactly. Presses the value of the node element accessed by slow into a stack. Thereafter slow continues to access the tail of the linked list, while the stack elements start out of the stack (in the case of odd number of elements to skip the middle element), compare two element values, once the occurrence of unequal, it is not a palindrome, otherwise. The time complexity of the solution is O (n), because one iteration is required, and an O (n) space is used as a stack to hold the list element.
Here are the implementations of the two methods
Idea One:
Idea two:
Public BooleanIspalindrome (ListNode head) {if(head==NULL) return true; if(head!=NULL&& head.next==NULL) return true; ListNode Slow=Head; ListNode Fast=Head; Booleanskip=false; Stack<Integer> stack=NewStack<integer>(); while(slow!=NULL) { if(fast==NULL)//an even number of{Skip=true; if(slow.val!=Stack.pop ())return false; } if(fast!=NULL&& fast.next==NULL)//Odd number of { if(!skip) Slow=Slow.next; Skip=true; if(slow.val!=Stack.pop ())return false; } if(!skip) Stack.push (Slow.val); Slow=Slow.next; if(fast!=NULL&& fast.next!=NULL) {Fast=Fast.next.next; } } return true; }
Leetcode palindrome linklist