Created
January 24, 2014 18:50
-
-
Save tolinwei/8603596 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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