使用栈实现回文判定C++

#include 
#include 

using namespace std;

typedef char elemType;
typedef struct stackNode {
    elemType data;
    struct stackNode *next;
} stackNode, *S;

bool initStack(S &s) {
    s = NULL;
    return true;
}

bool push(S &s, elemType e) {
    S p;
    p = new stackNode;
    if (!p) return false;
    p->data = e;
    p->next = s;
    s = p;
    return true;
}

bool pop(S &s, elemType &e) {
    if (!s) return false;
    S p;
    p = s;
    s = s->next;
    e = p->data;
    delete p;
    return false;
}

bool getTop(S s, elemType &e) {
    if (!s) return false;
    e = s->data;
    return true;
}

bool isEmpty(S s) {
    if (!s) return true;
    else return false;
}

bool palindrome(char *str) {
    S s;
    int len, i;
    char e;
    len = strlen(str) / 2;
    initStack(s);
    for (i = 0; i < len; i++) {
        push(s, str[i]);
    }
    if (len % 2 == 1) i++;
    while (!isEmpty(s)) {
        pop(s, e);
        if (e != str[i]) return false;
        else i++;
    }
    return true;
}

int main() {
    char str[]{"aecbcea"};
    if (palindrome(str)) cout << "It's palindrome!" << endl;
    return 0;
}

Output:

It's palindrome!

你可能感兴趣的:(使用栈实现回文判定C++)