我为我的链表创建了回文函数,但遗憾的是它似乎没有用! ,我相信它没有语法错误,当我运行该程序时,问题是合乎逻辑的,无论链表是什么,它总是给我“ Not Palindrome”的信息。

这是代码:

#include <iostream>
using namespace std;

struct node
{
    int info;
    node *link;
};


class Linked_List
{
private:
    int count;
    node *first;
    node *last;
    node *current;

public:
    Linked_List()
    {
        count=0;
        first=NULL;
        last=NULL;
    }

    void Initialize_List()
    {
        cout<<"Enter Number OF Nodes"<<endl;
        cin>>count;

        first=last=current=new node;

        for(int i =0;i<count;i++)
        {
            cout<<"Enter New Node Info :"<<endl;
            cin>>current->info;
            last->link=current;
            last=current;
            current=new node;
        }

        last->link=NULL;
    }

    bool Is_Empty()
    {
        if(first==NULL)
        {
            return true;
        }

        else
        {
            return false;
        }
    }

    int Front ()
    {
        if (first != NULL)
            return first-> info;
        else return 0;
    }

    int Back ()
    {
        if (last != NULL)
            return last-> info;
        else return 0;
    }

    void Delete_First()
    {
        if (!Is_Empty())  // Or if(first==NULL)
        {
            node *p;
            p=first;
            first=first->link;
            delete p;
            count --;
            if (count==0)
                first=last=NULL;
        }
    }

    friend bool Palindrome();
};

bool Palindrome (Linked_List & n)
{
    {
        while (!n.Is_Empty())
        {
            if (n.Front()!=n.Back())
            {
                cout<<"Not Palindrome"<<endl;
                return false;
            }
            else
            {
                n.Delete_First();
                n.Delete_First();
            }
        }
    }

    cout<<"Palindrome"<<endl;  return true;
}


void main ()
{
    Linked_List obj;

    cout<<"Is the list empty ?"<<"  "<<boolalpha<<obj.Is_Empty(); cout<<endl;

    obj.Initialize_List();

    cout<<"Is the list empty ?"<<"  "<<boolalpha<<obj.Is_Empty(); cout<<endl;

    Palindrome(obj);
}

===============>>#1 票数:1 已采纳

您需要从左侧删除一个,从右侧删除一个,还要考虑元素奇数的情况:

n.Delete_First();
if (!n.Is_Empty()) 
    n.Delete_Last();

  ask by Franky translate from so

未解决问题?本站智能推荐: