Skip to content

Instantly share code, notes, and snippets.

@tolinwei
Created January 24, 2014 18:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tolinwei/8603596 to your computer and use it in GitHub Desktop.
Save tolinwei/8603596 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <stack>
using namespace std;
class Node
{
public:
int value;
Node *next;
Node(int v) : value(v) {}
};
/*
1 2 3 2 3
1 2 3 2
*/
bool check_pal(Node *head)
{
stack<int> temp;
Node *fast = head;
Node *slow = head;
while (!(fast == NULL || fast->next == NULL)) { //important logic
temp.push(slow->value);
slow = slow->next;
fast = fast->next->next;
}
if (fast != NULL) {
slow = slow->next;
}
while (!temp.empty()) {
if (temp.top() != slow->value) {
return false;
}
temp.pop();
slow = slow->next;
}
return true;
}
int main(int argc, char *argv[]) {
Node *head = new Node(1);
Node *a = new Node(2);
Node *b = new Node(3);
Node *c = new Node(2);
Node *d = new Node(3);
head->next = a;
a->next = b;
b->next = c;
c->next = d;
cout << check_pal(head) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment