判断是否是回文链表(快慢指针+栈)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Legends_Never_Die/article/details/83690190
bool is_palin(Node*h)
{
    Node*quick,*slow,*p,*n;
    stack<int>s;
    if(h==NULL || h->next==NULL)return false;
    quick=slow=h;
    while(1)
    {
        if(quick->next==NULL || quick->next->next==NULL)
        {
            n=h;
            if(quick->next==NULL)
            {
                p=slow;//记下中间节点的位置
            }
            else
            {
                p=slow->next;
            }
            slow=slow->next;
            while(slow!=NULL)
            {
                s.push(slow->key);
                slow=slow->next;
            }
            while(!s.empty())
            {
                if(s.top()==n->key)
                {
                   s.pop();
                   n=n->next;
                }
                else
                {
                    while(!s.empty())s.pop();
                    return false;
                }
            }
            if(n==p)return true;
        }
        slow=slow->next;
        quick=quick->next->next;
    }
}

猜你喜欢

转载自blog.csdn.net/Legends_Never_Die/article/details/83690190