Question

I made Palindrome Function For my linked list but sadly it doesn't seems it works ! , It has no syntax error i believe , the problem is logical when i run the program , It always gives me "Not Palindrome " whatever the linked list is .

here is the code :

#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);
}
Was it helpful?

Solution

You need to delete one from the left side and one from the right side, and also consider the case of odd number of elements:

n.Delete_First();
if (!n.Is_Empty()) 
    n.Delete_Last();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top