用C#描述数据结构的栈和队列的方法判断是否为回文。

如题所述

//-----------以下是判断方法,堆栈和队列的创建方法很普通,如果你还要的话再补充------------
//采用堆栈判断回文
//思路就是:利用栈的后进先出的方法,将目标字符串先压入一个栈
//如果该字符串是回文,则他的出栈序列就与原序列相同
//采用队列判断回文
//与堆栈正好相反,利用先进先出
bool Check(char[] target)
{
//创建一个栈或队列的实例
StackOrQueue temp = new StackOrQueue();

//将目标字符串压入栈或队列
for(int i = 0; i < target.Length; i++)
temp.push(target[i]);

//利用栈或队列的性质,判断是否为回文
for(int i = 0; i < target.Length; i++)
//for(int i = target.Length - 1; i > 0; i--) 如果是队列法只需要将上句改为这句
if(temp.pop() != target[i])
return false;

return true
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-10-12
class ReplyWord
{
/// <summary>
/// 判断是否回文
/// </summary>
/// <param name="item">所要判断的字符串</param>
/// <returns>是就返回true,否就返回false</returns>
public static bool IsReplyWord(string item)
{
if (item.Length == 0) return false;
IStack<string> WordStack = new LinkStack<string>();//新建一个对象栈,用来存储所要判断的字符
IQueue<string> WordQueue = new LinkQueue<string>();//新建一个对象队列,也是用来存储所要判断的字符
//将字符串入栈,和入队
for (int i = 0; i < item.Length; i++)
{
WordStack.Push(item.Substring(i, 1));//将字符逐个入栈
WordQueue.In(item.Substring(i, 1));//将字符逐个入队
}
while (!WordStack.IsEmpty && !WordQueue.IsEmpty)
{
//栈是后进先出,队列是先进先出
//刚好将出栈元素与出队元素相比较,不相等则不是回文
if (WordStack.Pop() != WordQueue.Out())
{
return false;//发现不相等则返回false
}
}
return true;//经过比较后没有发现不相等,则是回文,返回true
}
}

class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("检测回文演示:\n------------------------------------------------------");
Console.WriteLine("请输入你要检测的字符(-1退出):");
string input = Console.ReadLine();
if (input == "-1") return;
if (ReplyWord.IsReplyWord(input))
{
Console.WriteLine("你的所输入的字符'{0}'是回文!", input);
}
else
{
Console.WriteLine("不好意思,你的所输入的字符'{0}'不是回文!", input);
}
Console.WriteLine("按任意键继续...");
Console.ReadKey();
Console.Clear();
}

}
}