isListPalindrome | Linked List | Data Structure

CODE:

// Singly-linked lists are already defined with this interface:
// template<typename T>
// struct ListNode {
//   ListNode(const T &v) : value(v), next(nullptr) {}
//   T value;
//   ListNode *next;
// };
//
bool isListPalindrome(ListNode<int> * l) {
    ListNode<int> * fast=l;
    ListNode<int> *slow =l;
    while(fast != nullptr && fast->next != nullptr){
            fast = (fast->next)->next;
            slow = slow->next;
        }
        
    ListNode<int> *current = slow;
    ListNode<int> *prev = NULL;
    ListNode<int> *next = NULL;
    while (current != NULL) { 
            // Store next 
            next = current->next; 
  
            // Reverse current node’s pointer 
            current->next = prev; 
  
            // Move pointers one position ahead. 
            prev = current; 
            current = next; 
        } 
        slow = prev;

        fast = l;
        
        while(slow != NULL){
            
            if(fast->value != slow->value){
                return false;
            }
            fast = fast->next;
            slow = slow->next;
        }

        return true;
}

Leave a Reply

Your email address will not be published. Required fields are marked *