只用栈与队列实现判断回文

#include<iostream>
using namespace std;
template<typename E>class Node {
public :
	E data;
	Node * next;
	Node(E it, Node *p = NULL) {
		data = it; next = p;
	}
	Node(Node *p = NULL) {
		next = p;
	}
};
template<typename E> class LStack {
public :
	Node<E> * head;
	int cnt;
	LStack() { head = NULL; cnt++; }
	~LStack() {
		while (head != NULL) {
			Node<E> * p = head;
			head = head->next;
			delete p;
		}
		cnt = 0;
	}
	void push(const E& it) {
		cnt++;
		head = new Node<E>(it, head);
	}
	E pop() {
		cnt--;
		Node<E> *temp = head->next;
		E it = head->data;
		delete head;
		head = temp;
		return it;
	}
	int length() { return cnt; }
};
template<typename E> class LQueue {
public :
	Node<E> * head;
	Node<E> * tail;
	int cnt;
	LQueue() {
		head = tail = new Node<E>();
		cnt = 0;
	}
	~LQueue() {
		while (head->next!=NULL) {
			tail = head->next;
			delete tail;
		}
		tail = head;
		delete head;
		cnt = 0;
	}
	void enqueue(E it) {
		tail->next = new Node<E>(it, NULL);
		tail = tail->next;
		cnt++;
	}
	E dequeue() {
		Node<E> * temp = head->next;
		E it = temp->data;
		if (temp == tail) tail = head;
		cnt--;
		head->next = temp->next;
		delete temp;
		return it;
	}
	int length() { return cnt; }
};
int main() {
	char c;
	LQueue<char> allchar;
	LQueue<char> fronthalf;
	LStack<char> rearhalf;
	while ((c = cin.get()) != '\n')
		allchar.enqueue(c);
	//for (Node<char> *p = allchar.head->next; p != NULL; p = p->next)
	//	cout << p->data ;
	int num = allchar.length();
	int i;
	for (i = 0; i < num / 2; i++)
		fronthalf.enqueue(allchar.dequeue());
	if (num % 2 != 0) {
		allchar.dequeue(); i++;
	}
	for (; i < num; i++)
		rearhalf.push(allchar.dequeue());
	for ( i = 0; i < num / 2; i++)
		if (fronthalf.dequeue() != rearhalf.pop())
			break;
	if (i == num / 2) cout << "TRUE";
	else cout << "FALSE";
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值