Answer to Question #270713 in C++ for osama

Question #270713

Write a function to check whether given singly linked list is palindrome or not. also give main for the function.


1
Expert's answer
2021-11-25T00:53:52-0500
#include <iostream>
#include <string>
using namespace std;
class Node{
    public:
    char data;
    Node *next, *prev;
    Node();
    Node(char);
};
Node::Node(){
    next = NULL;
    prev = NULL;
}
Node::Node(char data){
    this->data = data;
    next = NULL;
    prev = NULL;
}
class LL{
    Node *head; 
    int size;


    public:
    LL();
    void insert(char);
    void remove(char);
    bool isPalindrome();
    void print();
};
LL::LL(){
    size = 0;
    head = NULL;
}
void LL::insert(char data){
    Node *temp = new Node(data);
    Node *curr = head;
    if(curr == NULL){
        temp->next = head;
        head = temp;
        return;
    }
    while(curr->next != NULL){
        curr = curr->next;
    }
    temp->next = curr->next;
    curr->next = temp;
    size++;
}
void LL::remove(char data){
    Node* curr = head;
    Node* prev = NULL;
    Node* temp = NULL;
    while(curr != NULL){
        if(curr->data == data){
            if(prev == NULL){
                temp = head;
                head = head->next;
                curr = head;
                delete temp;
                size--;
            }
            else{
                temp = curr;
                if(curr->next != NULL){
                    prev->next = curr->next;
                }
                else{
                    prev->next = NULL;
                }
                curr = curr->next;
                delete temp;
                size--;
            }
        }
        else{
            prev = curr;
            curr = curr->next;
        }
    }
}


bool LL::isPalindrome(){
    Node* curr = head;
    string s = "";
    string rev = "";
    while(curr != NULL){
        s += curr->data;
        rev = curr->data + rev;
        curr = curr->next;
    }  
    return s == rev;
}


int main(){
    LL list, list2;
    list.insert('g');
    list.insert('a');
    list.insert('g');


    list2.insert('h');
    list2.insert('e');
    list2.insert('l');


    if(list.isPalindrome()){
        cout<<"List 1 is palindrome\n";
    }
    else cout<<"List 1 is not a palindrome\n";


    if(list2.isPalindrome()){
        cout<<"List 2 is palindrome\n";
    }
    else cout<<"List 2 is not a palindrome\n";
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS