回归列表的回文函数

时间:2014-04-21 03:08:41

标签: c++ linked-list boolean nodes palindrome

我制作了Palindrome功能对于我的链接列表但遗憾的是它似乎不起作用! ,它没有语法错误我相信,当我运行程序时问题是合乎逻辑的,它总是给我" 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 个答案:

答案 0 :(得分:1)

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

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