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
Post a Comment