栈:在数据结构里,我们都知道是以后进先出的方式的一种数据结构。
在C# 中也有很大的用处。Stack 也是一种泛型类。
最基本的两种操作:Push(T) 和Pop()方法
下面是我的两个例子
/// <summary>
/// 利用栈 检测字符串是否回文
/// 回文:正反相同的字符串
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
/// 利用栈 检测字符串是否回文
/// 回文:正反相同的字符串
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static bool IsP1(string text)
{
int count = 0;
int index = 0;
bool yes = false;
{
int count = 0;
int index = 0;
bool yes = false;
Stack<string> stack = new Stack<string>();
for (int i = 0; i < text.Length; i++)
{
stack.Push(text[i].ToString());
}
{
stack.Push(text[i].ToString());
}
count = text.Length / 2;
while (count != 0)
{
string temp = stack.Pop();
if (temp == text[index].ToString())
{
yes = true;
while (count != 0)
{
string temp = stack.Pop();
if (temp == text[index].ToString())
{
yes = true;
}
else
{
yes = false;
return yes;
}
index++;
count--;
}
else
{
yes = false;
return yes;
}
index++;
count--;
}
return yes;
}
public static bool IsP2(string text)
{ //第二种方法,简单点,呵呵
{ //第二种方法,简单点,呵呵
Stack<char> stack = new Stack<char>();
for (int i = 0; i < text.Length; i++)
{
stack.Push(text[i]);
}
{
stack.Push(text[i]);
}
char[] temp = new char[text.Length];
for (int i = 0; i < temp.Length; i++)
{
temp[i] = stack.Pop();
}
{
temp[i] = stack.Pop();
}
string str = new string(temp);
return str == text;
return str == text;
}
/// <summary>
/// 判断表达式中圆括号的匹配是否正确,如果不正确输出错误的位置。
/// 如:((a+b)*c) 这个正确
/// ((((((a+b)*c 和((a+b)*C)))))这两个错误
/// </summary>
/// <param name="exp"></param>
/// <returns></returns>
public static bool CheckExpression(string exp)
{
Stack<int> stack = new Stack<int>();
/// 判断表达式中圆括号的匹配是否正确,如果不正确输出错误的位置。
/// 如:((a+b)*c) 这个正确
/// ((((((a+b)*c 和((a+b)*C)))))这两个错误
/// </summary>
/// <param name="exp"></param>
/// <returns></returns>
public static bool CheckExpression(string exp)
{
Stack<int> stack = new Stack<int>();
for (int i = 0; i < exp.Length; i++)
{
if (exp[i] == '(')
{
//把当前左括号的位置入栈,而不是把数组的值入栈!
stack.Push(i);
}
if (exp[i] == ')')
{
if (stack.Count != 0)
{
stack.Pop();
}
else
{
Console.WriteLine("错误的位置:{0}",i);
return false;
}
}
}
{
if (exp[i] == '(')
{
//把当前左括号的位置入栈,而不是把数组的值入栈!
stack.Push(i);
}
if (exp[i] == ')')
{
if (stack.Count != 0)
{
stack.Pop();
}
else
{
Console.WriteLine("错误的位置:{0}",i);
return false;
}
}
}
if (stack.Count != 0)
{
Console.WriteLine("错误的位置:{0}", stack.Pop());
return false;
}
{
Console.WriteLine("错误的位置:{0}", stack.Pop());
return false;
}
return true;
}
转载于:https://blog.51cto.com/edward911/315738