Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stack>
- using namespace std;
- class node{
- protected:
- int element;
- node* link;
- public:
- //constructor that accepts only element
- node(int element) {
- this->element = element;
- this->link = NULL;
- }
- //constructor that accepts both link and element
- node(int element, node* link){
- this->element = element;
- this->link = link;
- }
- //method to update the element
- void updateData(int element){
- this->element = element;
- }
- //method to update or setup link
- void updateLink(node* link){
- this->link = link;
- }
- //method to get the element from the node
- int getElement(){
- return this->element;
- }
- //method to get the next node
- node* getNextNode(){
- return this->link;
- }
- };
- // checking if linked list is a palindrome
- bool isPalindrome(node* right){
- if(right == NULL){
- return true;
- }
- static node* left = right;
- if(right->getNextNode() != NULL){
- right = right->getNextNode();
- isPalindrome(right);
- }
- if(left->getElement() == right->getElement()){
- left = left->getNextNode();
- return true;
- }
- }
- class Linkedlist {
- public:
- node *head;
- //constructor for the Linked List class
- Linkedlist() {
- head = NULL;
- }
- //returns head node
- node *getHead() {
- return this->head;
- }
- // method to add a node at the end
- void insert(int element) {
- node *tempNode = new node(element);
- node *p = head;
- if (head == NULL) {
- head = tempNode;
- return;
- }
- else {
- while (p->getNextNode() != NULL) {
- p = p->getNextNode();
- }
- p->updateLink(tempNode);
- return;
- }
- }
- //method to display all the elements of the Linked List
- void display() {
- cout << "\n";
- node *tempNode = head;
- while (tempNode != NULL) {
- if (tempNode->getNextNode() != NULL)
- cout << tempNode->getElement() << " --> ";
- else
- cout << tempNode->getElement();
- tempNode = tempNode->getNextNode();
- }
- return;
- }
- };
- int main() {
- cout<<"Program to check if a Linked List is Palindrome or not";
- Linkedlist l1;
- l1.insert(1);
- l1.insert(3);
- l1.insert(5);
- l1.insert(7);
- l1.insert(7);
- l1.insert(8);
- l1.insert(5);
- l1.insert(3);
- l1.insert(1);
- cout<<"\nLinked list is : ";
- l1.display();
- if(isPalindrome(l1.getHead()))
- cout<<"\nThe given Linked List is Palindrome";
- else
- cout<<"\nThe given Linked List is not a Palindrome";
- return 0;
- }
Add Comment
Please, Sign In to add comment