gpt4 book ai didi

c++ - 堆栈和队列以测试回文

转载 作者:行者123 更新时间:2023-11-28 06:18:33 25 4
gpt4 key购买 nike

我制作了一个自定义 Stack 和 Queue 类。在我的程序中,我想同时使用它们来测试单词或短语是否为回文。但是,我需要更改 Stack 和 Queue 类,这将允许数字和字符串。我将如何以简单的方式解决这个问题?我阅读了有关使用 Palindromes 时遇到问题的人的信息,但这是与 C++ 引用类有关的。有任何想法吗?这是我处理数字的代码。

//Queue.h

#include <iostream>
using namespace std;

class Queue
{
public:
Queue();
~Queue();
void enqueue(int);
int dequeue();
void print();
private:
typedef struct Node {
Node *link_;
int item_;
} NODE;
NODE* head_;
};

Queue::Queue()
{
head_ = NULL;
}

Queue::~Queue()
{
if (head_ == NULL) return;
NODE *cur = head_;
while (cur) {
Node *ptr = cur;
cur = cur->link_;
delete ptr;
}
}

void Queue::enqueue(int n)
{
if (head_ == NULL) {
head_ = new NODE;
head_->item_ = n;
head_->link_ = NULL;
return;
}
NODE *cur = head_;
while (cur) {
if (cur->link_ == NULL) {
NODE *ptr = new NODE;
ptr->item_ = n;
ptr->link_ = NULL;
cur->link_ = ptr;
return;
}
cur = cur->link_;
}
}

void Queue::print()
{
if (head_ == NULL) return;
Node *cur = head_;
cout << "This is your current queue: " << endl;
while (cur) {
cout << cur->item_ << " ";
cur = cur->link_;
}
cout << endl;
}

int Queue::dequeue()
{
if (head_ == NULL) {
cout << "This is an empty queue!!" << endl;
return NULL;
}
NODE *tmp = head_;
int value = head_->item_;
if (head_->link_) {
head_ = head_->link_;
}
// pop the last element (head)
else {
delete tmp;
head_ = NULL;
}
cout << "You dequeued: " << value << endl;;
return value;
}

int getQueue()
{
Queue *que = new Queue();
que->enqueue(15);
que->enqueue(75);
que->enqueue(105);
que->enqueue(25);
que->enqueue(55);
que->print();
que->dequeue(); que->print();
que->dequeue(); que->print();
que->dequeue(); que->print();
que->dequeue(); que->print();
que->dequeue(); que->print();
que->dequeue(); que->print();
return 0;
}

我真的是 C++ 编码的新手,真的很想学习。如果有人能帮助我,我将不胜感激。

最佳答案

最好的方法是使您的队列类型模板化

template <typename T> class Queue
{
public:
Queue();
~Queue();
void enqueue(const T &value);
T dequeue();
void print();
private:
typedef struct Node {
Node *link_;
T item_;
} NODE;
NODE* head_;
};

现在你可以把它当作

Queue<int> intQueue;
intQueue.enqueue(1);
intQueue.enqueue(2);
int i = intQueue.dequeue();

Queue<string> stringQueue;
stringQueue.enqueue("hello");

Queue<char> charQueue;
charQueue.enqueue('c');

关于c++ - 堆栈和队列以测试回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29762340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com