- // ------------------算法二:利用栈先进后出,队列先进先出的特点----------------
- //abba
- Console.WriteLine("算法2:请输入一个字符串!");
- //调用.net里面自带的Queue,Stack,并初始化
- Queue<char> queue = new Queue<char>();
- Stack<char> stack = new Stack<char>();
- string str2 = Console.ReadLine(); //获取输入字符
- for (int i = 0; i < str2.Length; ++i) //放入栈和队列
- {
- queue.Enqueue(str2[i]);
- stack.Push(str2[i]);
- }
- IsHuiWen(queue, stack);
- //检验函数,只需要检验1/2的位置,因为只需要检测前半部分和后半部分是否相同。
- static void IsHuiWen(Queue<char> queue, Stack<char> stack)
- {//aabb /abbaa
- //abcd
- // abbba
- int i = 0, total = 0;
- bool isHuiWen = true;
- //确定所要取出的字数,分奇数偶数两种情况
- if (queue.Count % 2 == 0)
- total = queue.Count / 2;
- else
- total = queue.Count / 2 + 1;
- //通过循环比对出栈元素和出队元素是否相同
- while (queue.Count != 0 && stack.Count != 0)
- {
- if (queue.Dequeue() != stack.Pop()) //不相等
- {
- isHuiWen = false;
- break;
- }
- else if (i == total) //检查到一半时,跳出循环
- break;
- ++i;
- }
- if (!isHuiWen)
- Console.WriteLine("这不是回文");
- else
- Console.WriteLine("这是回文");
- }
- //该片段来自于http://www.codesnippet.cn/detail/080820135037.html
来源: http://www.codesnippet.cn/detail/080820135037.html