Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Created January 31, 2015 00:13
Show Gist options
  • Save dgodfrey206/738aa17ede7de9267d5b to your computer and use it in GitHub Desktop.
Save dgodfrey206/738aa17ede7de9267d5b to your computer and use it in GitHub Desktop.
Palindrome for singly linked list
#include <iostream>
#include <unordered_set>
struct node
{
node(int data, node* next = nullptr)
: data(data)
, next(next)
{ }
int data;
node* next;
};
void push(node*& n, int value)
{
node** cur = &n;
while (*cur)
cur = &cur[0]->next;
*cur = new node(value);
}
void push(node*& n, std::initializer_list<int> v)
{
for (auto& x : v)
push(n, x);
}
void display(node* n)
{
if (n)
{
std::cout << n->data << " ";
if (!n->next) std::cout << '\n';
display(n->next);
}
}
int count(node* head, int value)
{
int c = 0;
while (head)
{
if (head->data == value)
++c;
head = head->next;
}
return c;
}
void reverse(node*& head)
{
node *curr = head,
*prev = nullptr,
*next;
while (curr)
{
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head = prev;
}
bool hasLoop(node* head)
{
for (std::unordered_set<node*> set; head; head = head->next)
{
if (set.find(head) != set.end())
return true;
set.insert(head);
}
return false;
}
bool hasLoopCycle(node* head)
{
node *first = head, *second = head;
while (first->next)
{
first = first->next->next;
second = second->next;
if (first == second)
return true;
}
return false;
}
node* getMid(struct node *head)
{
struct node *slow_ptr = head;
struct node *fast_ptr = head;
if (head!=NULL)
{
while (fast_ptr != NULL && fast_ptr->next != NULL)
{
fast_ptr = fast_ptr->next->next;
slow_ptr = slow_ptr->next;
}
}
return slow_ptr;
}
bool isPalindrome(node* head)
{
node *middle = getMid(head),
*temp;
reverse(middle);
temp = middle;
for (node* curr = head; temp; curr = curr->next, temp = temp->next)
{
if (curr->data != temp->data)
return false;
}
reverse(middle);
return true;
}
// 1 2 3 4 3 2 1
int main()
{
node* head = nullptr;
push(head, {1, 2, 3, 2, 1, 0});
std::cout << isPalindrome(head);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment