题目:
123454321,为回文串
判断已知链表是否是回文链表。
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Palindrome {
public:
bool isPalindrome(ListNode* pHead) {//利用快慢指针来实现;
// write code here
if(pHead==NULL)
return true;
ListNode *p=pHead;
ListNode *q=pHead;
stack <int> st;
st.push(q->val);
while(p->next!=NULL&&p->next->next!=NULL)
{
q=q->next;
st.push(q->val);
p=p->next->next;
}
if(p->next==NULL)//判断是否为奇数个结点;
st.pop();
q=q->next;//慢指针遍历到链表中间,依次将入栈的结点出栈,判断后半段结点是否与前半段结点相同;
while(!st.empty())
{
if(q->val!=st.top())
break;
q=q->next;
st.pop();
}
if(st.empty())
return true;
else
return false;
}
};