码迷,mamicode.com
首页 > 其他好文 > 详细

回文链表

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

标签:lin   false   class   ase   元素   int   ext   public   struct   

题目描述

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

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

回文链表

标签:lin   false   class   ase   元素   int   ext   public   struct   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!