回文链表

题目描述

请编写一个函数,检查链表是否为回文。

给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。

测试样例:
{1,2,3,2,1}
返回:true
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
class Palindrome {
public:
    bool isPalindrome(ListNode* pHead) {
        // write code here
        stack<int> s;
        ListNode *fast = pHead;
        ListNode *slow = pHead;

        while (fast != NULL && fast->next != NULL) {
            s.push(slow->val);
            fast = fast->next->next;
            slow = slow->next;
        }

        //有奇数个元素,跳过中间元素
        if (fast != NULL) {
            slow = slow->next;
        }

        while (slow != NULL) {
            int top = s.top();
            s.pop();
            if (top != slow->val)
                return false;
            slow = slow->next;
        }

        return true;
    }
    
};

 

{1,2,3,2,3}
返回:false

posted on 2017-04-01 23:47  123_123  阅读(99)  评论(0编辑  收藏  举报