判断链表是否满足回文标准:将链表分为二段,前一半正常不动,后一半进行反转,然后遍历前半段和后半段的链表节点元素,逐一比对元素属性值,判断是否满足回文标准。
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head==NULL)
{
return 1;
}
ListNode *mid=head,*right=head;
int node=1;
while(right->next!=NULL)
{
right=right->next; //point to the last node
node++;
}
for(int i=0;i<node/2;i++)
mid=mid->next; //mid points to the mid-node
// mid=mid->next;
ListNode *temp=(ListNode*)malloc(sizeof(ListNode)); // the head of the new list
temp->next=NULL; //the head node is null
while(mid!=NULL)
{
ListNode *flag=(ListNode*)malloc(sizeof(ListNode));
flag->val=mid->val;
flag->next=temp->next;
temp->next=flag;
mid=mid->next;
} //reverse the last part of the link-list
temp=temp->next; // the val of head node is null ,so points to the next node of the head node
while(temp!=NULL)
{
if(temp->val!=head->val)
return 0;
else
{
temp=temp->next;
head=head->next;
}
} //link-list node matching
return 1;
}
};