首页 > 其他 > 详细

回文链表

时间:2017-04-02 00:56:03      阅读:225      评论:0      收藏:0      [点我收藏+]

题目描述

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

给定一个链表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

回文链表

原文:http://www.cnblogs.com/xiuxiu55/p/6657932.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!