Palindrome Linked list







/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution
{
public:
    ListNode *node;
    ListNode *rev(ListNode *head)
    {
        ListNode *current = head, *prev = 0, *nextt;
        if (head == 0 || head->next == 0)
            return head;
        while (current != 0)
        {
            nextt = current->next;
            current->next = prev;
            prev = current;
            current = nextt;
        }
        return prev;
    }
    bool isPalindrome(ListNode *head)
    {
        //find the mid of linked list.
        //reverse the lined list from mid.
        //check from beginning and from next to middle for same values.
        ListNode *fast, *slow, *temp = head;
        fast = head;
        slow = head;
        while (fast != 0 && fast->next != 0 && fast->next->next != 0)
        {
            slow = slow->next;
            fast = fast->next->next;
        }
        // cout<<slow->val<<endl;
        slow->next = rev(slow->next);
        ListNode *t = head;
        slow = slow->next;
        while (slow != 0)
        {
            if (slow->val != temp->val)
                return false;
            slow = slow->next;
            temp = temp->next;
        }
        return true;
    }
};

Comments

Popular posts from this blog

First_Come_First_Serve CPU Scheduling

Reversing stack Method 2 !! (One Helper Stack only)

Populating Next Right Pointers in Each Node in O(1) space (without queue and level order)

Calculate factorial of large numbers !! (Using Arrays)

Multiplication of large numbers (Given in string format)

Left View of Binary Tree (Method 1 using recursion)

Check Bracket Sequence

Image Multiplication

Boundary Traversal of binary tree

BST to greater sum tree