【数据结构】顺序栈判断一个字符串是否为回文串 作业3

在这里插入图片描述

sqStack.cpp

#include <iostream>
#include "Stack.h"

using namespace std;

int main() {
    Stack s1;
    if (!s1.push())
        cout << "error!" << endl;
    if (s1.palindromic()) {
        cout << s1.getStr() << "是回文数" << endl;
    } else {
        cout << s1.getStr() << "不是回文数" << endl;
    }
    system("pause");
    return 0;
}

Stack.cpp

#include <d2d1effecthelpers.h>

#include "Stack.h"

Stack::Stack() {
    size = MAX_SIZE;
    top = -1;
    data = new char[size];
    cin >> str;
};

Stack::Stack(int s) {
    size = s;
    top = -1;
    data = new char[size];
    cin >> str;
}

Stack::~Stack() {
    delete[] data;
}

bool Stack::push() {
    int i;
    if (!isFull()) {
        data[++top] = str[i];//top值先+1,然后压入
        i++;
        return true;
    }
    return false;

}

bool Stack::pop(char &e) {
    if (isEmpty()) { return false; }
    else {
        e = data[top--];  //先取top的值将其返回,然后top的值-1
    }
    return true;
}


bool Stack::isEmpty() {
    if (top == -1)
        return true;
    else
        return false;
}

bool Stack::isFull() {
    if (top + 1 == size)
        //size换成了MAX_SIZE是不对的,有参构造函数和有参构造函数
        return true;
    else
        return false;
}


bool Stack::palindromic() {

    char temp;
    for (int i = 0; data[i] != '\0'; ++i) {
        pop(temp);
        if (str[i] != temp)
            return false;
        return true;
    }

}

char * Stack::getStr(){
    return str;
}

Stack.h

//
// Created by 63400 on 2021/10/30.
//

#ifndef HOMEWORK_STACK_H
#define HOMEWORK_STACK_H

#include <iostream>
using namespace std;

const int MAX_SIZE = 100;

class Stack {
private:
    char * data; //指向数组的指针
    int size; //数组的大小
    int top; //栈顶
    char str[MAX_SIZE];
public:
    Stack();
    Stack(int );
    ~Stack();

    bool push(); //压栈
    bool pop(char &e); //出栈并返回出栈元素
    char getTop(); //获取栈顶元素
    bool isEmpty(); //判断栈是否为空
    bool isFull(); //判断栈是否为满
    void setNull(); //将栈设置为空
    bool palindromic(); //判断是否为回文串
    char * getStr();    //获取字符串
};


#endif //HOMEWORK_STACK_H


非栈版

在这里插入图片描述

课后作业(全)参考

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值