Topic
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could do it in O (n) time and O (1) space?
Ideas
Using the double pointer method to find the midpoint position of the linked list, the elements after the midpoint of the list (excluding the midpoint element) are flipped and then matched to the previous element one by one of the midpoint position of the linked list.
Code
/ *---------------------------------------* Date: 2015-07-18* sjf0115* title: 234.Palindrome Linked list* website: https:// leetcode.com/problems/palindrome-linked-list/* Result: ac* Source: leetcode* Blog:-----------------------------------------*/ #include <iostream>#include <Vector>using namespace std;struct listnode{int val; ListNode*Next ListNode (int x): Val (x), Next (NULL) {}};class Solution { Public: BOOL Ispalindrome (ListNode*Head) {if(Head==nullptr) {return true; }//if //Midpoint positionListNode*Slow=Head ListNode*Fast=Head -Next while(Fast&&Fast -Next) {Slow=Slow -Next Fast=Fast -Next -Next }//whileSlow=Slow -Next//FlipListNode*Q=Reverselist (slow);//Determine if it is a palindrome stringListNode*P=Head while(p&&Q) {if(p -Val!=Q -Val) {return false; }//ifP=P -Next Q=Q -Next }//while return true; }Private://FlipListNode*Reverselist (ListNode*Head) {if(Head==nullptr) {returnHead }//if //Head nodeListNode*Dummy= NewListNode (-1); ListNode*P=Head ListNode*NextNode=P -Next while(p) {NextNode=P -Next P -Next=Dummy -Next Dummy -Next=P P=NextNode; }//while returnDummy -Next }};int Main () {solution S; ListNode*Head= NewListNode (1); ListNode*Node2= NewListNode (2); ListNode*Node3= NewListNode (3); ListNode*Node4= NewListNode (4); ListNode*Node5= NewListNode (3); ListNode*Node6= NewListNode (2); ListNode*Node7= NewListNode (1); Head -Next=Node2; Node2 -Next=Node3; Node3 -Next=Node4; Node4 -Next=NODE5; Node5 -Next=Node6; Node6 -Next=Node7; BOOL Result=S.Ispalindrome (head);if(Result) {cout<<"It's a palindrome."<<Endl }//if Else{cout<<"Not a palindrome."<<Endl }//else return 0;}
Run time
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Leetcode]234.palindrome Linked List