判断一个链表是否是回文的。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
int len = getLength(head);
if(len==1||len==0)
return true;
int x = len%2==0?len/2:len/2+1;
ListNode* start = head;
ListNode* end =reverseNode(getNode(head,x));
while(end!=NULL)
{
if(start->val!=end->val)
return false;
start=start->next;
end=end->next;
}
return true;
}
ListNode* reverseNode(ListNode* root)
{
ListNode* term =root->next;
root->next = NULL;
while(term!=NULL)
{
ListNode* temp = term->next;
term->next = root;
root=term;
term = temp;
}
return root;
}
ListNode* getNode(ListNode* root,int pos)
{
int x=0;
while(root!=NULL)
{
if(x==pos)
return root;
x++;
root=root->next;
}
return root;
}
int getLength(ListNode* root)
{
int ans=0;
while(root!=NULL)
{
ans++;
root=root->next;
}
return ans;
}
};